实例化一个类,然后将其传递给 setInterval [英] Instantiating a class and then pass it to setInterval

查看:48
本文介绍了实例化一个类,然后将其传递给 setInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个疯狂的问题.我正在从一个类中实例化一个对象.然后我想从这个对象传递一个函数给 setInterval 函数.整个代码块通过 keyDown 事件执行.代码如下:

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

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

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]

为了完整起见:

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

有人看到失败了吗?

提前致谢!=)

P.S.:这不是重复的 因为我没有面对函数 function() 错误.如果我用 (instance.functionToBeExecuded, 200) 执行它,它什么也不会发生.

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

我得到一个带有window"的循环控制台输出.因此该函数在窗口的范围内执行.但为什么?以及如何解决?

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?

控制台输出:

窗口索引.html

推荐答案

解决方法是:使用另一个函数包装它而不是直接调用方法

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}

这篇关于实例化一个类,然后将其传递给 setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆