Friday, August 08, 2008

scope of javascript anonymous function


var foo = "test in global window";
function Constructor() {
this.foo = 'test in Constructor';
this.local = (function() {
alert(this.foo);
return "local";
}).apply(this);
this.globals = (function(){
alert(this.foo);
return "global";
})();
}
new Constructor();

In javascript, scope of anonymous functions is global.
匿名函数中的作用对象是全局的window对象,一般是不需要注意这点,但当在匿名函数中使用使用this就要小心,这个this是指向window的,如上所示可以用apply或者call来指定匿名函数作用于哪个对象上,但匿名函数如果在setTimeout/setInterval中使用的话则需要将this对象用别名如_self/self/_this/that替代后在匿名方法中使用,如下面二个参考文章所示。
Reference:http://yuweijun.blogspot.com/2008/05/test-scope-of-this-in-closure-and-in.html
http://www.dustindiaz.com/scoping-anonymous-functions/

No comments :