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?
Using
call
does not help here: it callssetTimeout
with yourthis
object, but the callback function itself is still called from the global scope. What you really want to do is something like this:Edit: If you really want something similar to the
call
approach, you can usebind
which binds thethis
value for a function:However, this is part of the new ECMAScript 5 spec which is not yet supported by all browsers.