setTimeout is a method of window object. "this" context refer to the window. But you can change its context in the following way. setTimeout does not support call method.
setTimeout(function() { alert(this); }, 0); //window
//setTimeout.call({}, function() { alert(this); }, 0); //not supported
setTimeout((function() { alert(this); }).call({}), 0); //object
eval is also a method of Global object, in the case of browse, this is window object. But is context defined by its Containing context. Eval also does not support call method
function Foo() {
this.TestContext = function() {
eval("alert(this==window);"); //show false
setTimeout(function() { alert(this == window); }, 0); //show true
}
}
var f = new Foo();
f.TestContext();
eval("alert(this);");
eval.call({}, "alert(this);");
//firefox does not support this, but IE support, but it does not change context
No comments:
Post a Comment