-->

Instantiating a class and then pass it to setInter

2019-08-01 10:13发布

问题:

I've a crazy problem. I'm instantiating an object from a class. Then I want to pass a function from this object to the setInterval function. The whole code block is executed with a keyDown event. Here's the code:

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

The strange thing is that it's getting executed once and then starts to loop an error which states (firebug): 27

SyntaxError: missing ] after element list


[object HTMLAudioElement]

For the sake of completeness:

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

Does anyone see some fails?

Thanks in advance! =)

P.S.: This is not a duplicate cause I'm not facing the function, function() error. If I'm executing it with (instance.functionToBeExecuded, 200) it happens just nothing.

What I've found out so far is that the problem must be in the 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's constructor)
 node.setAttribute("key", this.variable);
}

I'm getting a looping console output with "window". So the function is executed in the window's scope. But why? And how to work around?

Console output:

Window index.html

回答1:

The workaround would be: wrap it using another function instead of calling method directly

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

This would give output many of these:

Class {functionToBeExecuded: function}