Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Can';t get setInterval函数调用另一个函数,该函数在javascript中使用this.function\u名称_Javascript - Fatal编程技术网

Can';t get setInterval函数调用另一个函数,该函数在javascript中使用this.function\u名称

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

我在一个对象中有一个函数,它设置了一个调用另一个函数的间隔,但每当调用该间隔函数时,它都会给出一个错误,即uncaughttypeerror: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去做我想做的事情