gpt4 book ai didi

javascript - 实例化一个类,然后将其传递给 setInterval

转载 作者:行者123 更新时间:2023-11-28 00:30:18 25 4
gpt4 key购买 nike

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

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

奇怪的是,它只执行一次,然后开始循环一个错误,其中指出(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) 执行它,它什么也不会发生。

到目前为止我发现问题一定是在某种程度上的范围内。如果我这样做:

  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”的循环控制台输出。所以该函数是在窗口范围内执行的。但为什么?以及如何解决?

控制台输出:

窗口索引.html

最佳答案

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

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

这将给出许多这样的输出:

Class {functionToBeExecuded: function}

关于javascript - 实例化一个类,然后将其传递给 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29065901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com