使用setTimeout指定变量的作用域

Scope of a variable using setTimeout

本文关键字:作用域 变量 setTimeout 使用      更新时间:2023-09-26

我很高兴它的工作,但仍然有点困惑的是什么"me"变量的范围是在下面的代码。使用了一段时间,但不知道为什么它工作。

var timer=function(){
    this.timerMember=1;
    this.timerID=0;
    this.startTimer=function(){
        var me=this;
        this.timerID=setTimeout(function(){
            //shares scope with this.startTimer
            //timerMember is 2 here
            console.log(me.timerMember);
            // this is window
            console.log(this);
            // me doesn't exist in window
            console.log(this.me);
        },0);
//  this code gets executed before anonymous
//  timer function
//        clearTimeout(this.timerID);
        this.timerMember++;
    }
}
var t=new timer();
t.startTimer();

传递给setTimeout的匿名函数似乎与timer共享作用域。当匿名函数执行(me. timermemer =2)时,startTimer显然已经完成,所以当startTimer完成时,me变量应该超出范围。对我来说幸运的是,JavaScript保留它,直到匿名函数被执行(适用于所有浏览器),但我想知道这是否是正确的方式。这种行为是有意为之还是偶然的幸运?

这是设计。这叫做闭包。

当一个函数在另一个函数中定义时,外部函数中的局部变量被放在闭包中,这样即使在外部函数结束后,它们也可以继续存在。内部函数保留闭包,以便以后可以访问变量。