javascript setTimeout call error

2019-03-28 03:50发布

问题:

I want to invoke the window.setTimeot function with my custom scope so I use the call method, but there is something wrong.

function foo() {
    this.bar = function() {
        console.log("keep going");
        window.setTimeout.call(this,this.bar,100);
    }
    this.bar();
}

new foo;

under Firefox this prints to the console only 1 line and then nothing, and under google chrome it throws a TypeError.

What is the problem in my code?

回答1:

Using call does not help here: it calls setTimeout with your this object, but the callback function itself is still called from the global scope. What you really want to do is something like this:

function foo() {
    var self = this;
    this.bar = function() {
        console.log("keep going");
        window.setTimeout(function() { self.bar(); }, 100);
    }
    this.bar();
}

Edit: If you really want something similar to the call approach, you can use bind which binds the this value for a function:

window.setTimeout(this.bar.bind(this), 100);

However, this is part of the new ECMAScript 5 spec which is not yet supported by all browsers.