Javascript error setTimeout

I want to call the window.setTimeot function with my custom scope, so I use call , 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; 

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

What is the problem in my code?

+7
source share
1 answer

Using call here does not help: 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 to the function:

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

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

+8
source

All Articles