Can';t get setInterval函数调用另一个函数,该函数在javascript中使用this.function\u名称
我在一个对象中有一个函数,它设置了一个调用另一个函数的间隔,但每当调用该间隔函数时,它都会给出一个错误,即uncaughttypeerror:object[object Window]没有方法 这是我试图理解的代码Can';t get setInterval函数调用另一个函数,该函数在javascript中使用this.function\u名称,javascript,Javascript,我在一个对象中有一个函数,它设置了一个调用另一个函数的间隔,但每当调用该间隔函数时,它都会给出一个错误,即uncaughttypeerror:object[object Window]没有方法 这是我试图理解的代码 function test2() { this.timer; this.say = function(){ console.log("hi"); } this.start = function() { //starts the interval function
function test2() {
this.timer;
this.say = function(){
console.log("hi");
}
this.start = function() {
//starts the interval function
this.timer = setInterval(this.loop, 1000)
}
this.loop = function() {
//runs every 1 second
this.say(); //gives error -- Uncaught TypeError: Object [object Window] has no method 'say'
}
}
var test = new test2();
test.start();
谢谢你的帮助 当setInterval()
触发时,上下文是全局上下文(例如窗口),而不是您的对象。要在对象上调用方法并在该方法调用中适当设置this
的值,您需要一个单独的函数,在该函数中您可以在实际对象上调用方法,如下所示:
this.start = function() {
//starts the interval function
var self = this;
this.timer = setInterval(function() {
self.loop();
}, 1000)
}
仅供参考,在使用异步函数(如计时器或ajax)将上下文
this
保存到局部变量中时,这是非常常见的,这样即使this
在回调函数中不同,也可以从嵌入式回调函数中引用它(如您的示例所示)。这是一种常见的设计模式。我对此有一个独特的解决方案。我通过创建一个调用我的对象方法的函数来解决这个问题:
const globalSet = new globals();
function ut(){
globalSet.updateToasts();
}
setInterval(ut,15000);
它似乎欺骗了JS去做我想做的事情