Antony said:
While looking at some code I realized that the built in
setTimeout
function takes a string that is later
evaluated in the original caller's context.
This original context is always the global object (window). However, you
can perfectly use a function reference or a function expression instead
of a string as the first argument for setTimeout - this isn't supported
by old browsers though, which would then call the toString() method for
the function while evaluating the setTimeout first argument - test
accordingly.
function foo(){
var bar="hello, world!";
setTimeout(
function(){
alert(bar);
},
1000
);
}
Using a function expression is much more powerful than using a string
argument, since you can control the scope chain and add a specific scope
object, just for this function (either using an outer function or a
"with" statement).
---
setTimeout(
(function(){
var foo=0, bar=0;
return function(){
window.status="foo:"+foo+", bar:"+bar;
if(foo++<1000 && bar-->-1000)
setTimeout(arguments.callee, 50);
}
})(),
50
);
---
---
with({foo:0,bar:0}){
setTimeout(
function(){
window.status="foo:"+foo+", bar:"+bar;
if(foo++<1000 && bar-->-1000)
setTimeout(arguments.callee, 50);
},
50
);
}