Instantiating a class and then passing it to setInterval

I have a crazy problem. I am creating an object from a class. Then I want to pass a function from this object to the setInterval function. The entire block of code is executed with the keyDown event. Here's the code:

  function doKeyDown(e){
      var instance = new Class(e.keyCode);
      setInterval(instance.functionToBeExecuded(), 200);
  }

      

The weird thing is that it runs once and then starts looping an error that says (firebug):

SyntaxError: missing ] after element list


[object HTMLAudioElement]

      

For completeness:

Class.prototype.functionToBeExecuded = function(){
 var node = document.createElement("audio");
 //the key is stored in the object (from the Class constructor)
 node.setAttribute("key", this.variable);
}

      

Does anyone see that someone is not working?

Thanks in advance! =)

PS: This is not a duplicate . I don't come across function, function (). If I execute it with (instance.functionToBeExecuded, 200), it just happens.

What I have figured out so far is that the problem must be in scope somehow. If I do it like this:

  function doKeyDown(e){
      var instance = new Class(e.keyCode);
      setInterval(instance.functionToBeExecuded, 200);
  }

Class.prototype.functionToBeExecuded = function(){
 console.log(this);
 var node = document.createElement("audio");
 //the key is stored in the object (from the Class constructor)
 node.setAttribute("key", this.variable);
}

      

I am getting the output of an outline console with a "window". Thus, the function is executed in the window area. But why? And how to work?

Console output:

Window index.html

+1


source to share


1 answer


A workaround would be: wrap it with another function instead of calling the method directly

function doKeyDown(e){
  var instance = new Class(e.keyCode);
  setInterval(function(){
    instance.functionToBeExecuded()
  }, 200);
}

      



This will result in many of them being exited:

Class {functionToBeExecuded: function}

      

+1


source







All Articles