It is common knowledge that the setTimeout
function does not work correctly with this
because it executes in a global scope, causing this
to refer to the window
object.
To test this behavior, I created a simple test:
All you need to do is wrap it within a function:
var o={}
o.a=1;
o.m=function (){alert(this.a);}
setTimeout(
function (){
o.m() ;
}
,100);
When executed, it properly alerts 1
.
I wonder why no one has mentioned this solution before. Is there something I am missing? Does it behave differently?
p.s.: For those interested, here is a demo where this approach fails:
var o={}
o.a=1;
o.m=function (){alert(this.a);}
setTimeout( o.m ,100); //undefined