Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/414.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
Javascript 带有';这';_Javascript_Object_This_Settimeout - Fatal编程技术网

Javascript 带有';这';

Javascript 带有';这';,javascript,object,this,settimeout,Javascript,Object,This,Settimeout,可能重复: 我正在尝试对对象设置超时。通过一些测试代码(见下文),我希望减少TimeRPO,直到它达到0。当startTimer()第一次调用timerInc()时,我使用下面的代码时,它将达到3(如预期的那样)。当超时调用TimerInc()时,我将收到timerPos变量的“未定义”。我做错了什么 function start(){ var alert = new Alert(3); alert.startTimer(); } function Alert(timer) { th

可能重复:

我正在尝试对对象设置超时。通过一些测试代码(见下文),我希望减少TimeRPO,直到它达到0。当startTimer()第一次调用timerInc()时,我使用下面的代码时,它将达到3(如预期的那样)。当超时调用TimerInc()时,我将收到timerPos变量的“未定义”。我做错了什么

function start(){
var alert = new Alert(3);
alert.startTimer();

}
function Alert(timer) {
    this.timerMinutes = timer;
    this.timerPos = 0;

    this.startTimer = function() {
        this.timerPos = this.timerMinutes+1;
        this.timerInc();
    };


    this.timerInc = function() { 
        if (this.timerPos > 0){     
            this.timerPos--;   
                    // first time this function gets called timerPos is 3
                    // the second time when its called by the timeout it
                    // will be 'undefined'
            setTimeout(this.timerInc,1000);
        }   
    };
}
(在超时中使用this.timerInc()而不是this.timerInc对我不起作用,使用引号也不起作用)

您需要将“this”变量绑定到另一个显式使用的变量,因为“this”的值根据调用函数的人而变化

功能警报(计时器){
var that=this;//将此警报实例存储为“that”。
this.timerMinutes=计时器;
this.timerPos=0;
// ...
this.timerInc=函数(){
//使用警报实例“that”,而不是运行时绑定到“this”的任何对象。
如果(that.timerPos>0){
那就是时间点;
setTimeout(即.timerInc,1000);
}
};
}
问题在于
setTimeout()
函数将从全局范围调用其函数参数,而不是在注册时从封闭对象的范围调用。因此,在全局范围内,“this”变量绑定到“global”对象(可能是浏览器窗口)

您可以这样验证:

setTimeout(function(){alert(this);}, 500); // => alerts "[object DOMWindow]"

首先,您应该使用prototype来声明类Alert的方法。更改您调用的函数的范围将完成以下工作:

function start(){
var alert = new Alert(3);
alert.startTimer();

}
function Alert(timer) {
    this.timerMinutes = timer;
    this.timerPos = 0;
}

Alert.prototype.startTimer = function() {
        this.timerPos = this.timerMinutes+1;
        this.timerInc();
    };


Alert.prototype.timerInc = function() { 
    if (this.timerPos > 0){     
        this.timerPos--;
        console.log(this.timerPos);
        setTimeout(function(_this){_this.timerInc()},1000,this);
    }   
};

演示:在
这个函数内部。timerInc
这个
在被
setTimeout
调用时将引用
窗口
。工作演示:它仍然错误地引用函数内部的
这个
。@lwburk:查看我更新的答案;我忘了在所有必要的地方将“this”变量更新为“that”。这是可行的,但我肯定会使用prototype来声明警报的内部方法。