-->

实例化一个类,然后把它传递给setInterval(Instantiating a class an

2019-10-22 06:30发布

我有一个疯狂的问题。 我实例从一个类的对象。 然后,我想从这个对象传递函数的setInterval函数。 整个代码块与keyDown事件执行。 下面的代码:

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

奇怪的是,它越来越执行一次,然后开始循环其中指出错误(萤火虫):27

SyntaxError: missing ] after element list


[object HTMLAudioElement]

为了完整起见:

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);
}

有谁看到一些失败?

提前致谢! =)

PS: 这不是我不要对着函数,函数()错误重复的原因。 如果我有(instance.functionToBeExecuded,200)执行它它发生根本不值一提。

我已经发现了迄今为止的是,这个问题必须在某种程度上范围。 如果我不喜欢这样写道:

  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);
}

我越来越有“窗口”一个循环的控制台输出。 因此,该功能在窗口的范围内执行。 但为什么? 而如何解决?

控制台输出:

Window index.html

Answer 1:

解决方法是:使用其他功能,而不是直接调用方法,它包

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

这将使输出很多这样的:

Class {functionToBeExecuded: function}


文章来源: Instantiating a class and then pass it to setInterval