为什么这个Javascript方法不会自己调用?

Mic*_*ker 5 javascript methods settimeout

我有一个带有特权方法的JavaScript对象.当这个方法完成后,我希望它自己调用(在一个小的超时后)并继续无限期地运行.不幸的是,该方法只运行两次,然后停止没有任何错误(在Chrome和IE中测试具有相同的结果).

代码如下:

function Test() {
    // ... private variables that testMethod needs to access ...
    this.testMethod = function() {
        alert("Hello, from the method.");
        setTimeout(this.testMethod, 2000);
    };
}

var myTest = new Test();
myTest.testMethod();
Run Code Online (Sandbox Code Playgroud)

我希望每两秒钟收到一次警报,但它只显示警报两次,然后停止.你可以在这里看到一个实例.知道为什么会这样吗?

ben*_*ado 10

因为this函数外部函数内部不一样this.尝试改为:

function Test() {
    // ... private variables that testMethod needs to access ...
    var me = this;
    this.testMethod = function() {
        alert("Hello, from the method.");
        setTimeout(me.testMethod, 2000);
    };
}
Run Code Online (Sandbox Code Playgroud)


Pru*_*sse 6

当你第一次用"myTest.testMethod();"调用它时 "this"关键字绑定到"myTest"对象,当超时触发"window"对象绑定到"this"关键字时,"this.testMethod"等同于"window.testMethod".尝试:

function Test() {
    // ... private variables that testMethod needs to access ...
    this.testMethod = function() {
        alert("Hello, from the method.");
        setTimeout((function(self){
            return function(){self.testMethod();};
        })(this), 2000);
    };
}

var myTest = new Test();
myTest.testMethod();
Run Code Online (Sandbox Code Playgroud)

要么:

function Test() {
    // ... private variables that testMethod needs to access ...
    this.testMethod = function() {
        alert("Hello, from the method.");
        var self = this;
        setTimeout(function(){self.testMethod();}, 2000);
    };
}

var myTest = new Test();
myTest.testMethod();
Run Code Online (Sandbox Code Playgroud)