Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript setTimeout call error

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?

like image 512
Gergely Fehérvári Avatar asked May 24 '11 14:05

Gergely Fehérvári


1 Answers

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.

like image 182
casablanca Avatar answered Oct 13 '22 15:10

casablanca