可以't获取setInterval函数以使用javascript中的this.function_name调用另一

Can't get setInterval function to call another function using this.function_name in javascript

本文关键字:function this 中的 javascript name 调用 获取 函数 setInterval 可以      更新时间:2023-09-26

我在一个对象中有一个函数,它设置了一个调用另一个函数的间隔,但当调用该间隔函数时,它会给我一个错误,说Uncaught TypeError:object[object Window]没有方法

这是我正在努力理解的代码。

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去做我想做的事。