javascript里面的this其实是不容易理解的,就好像和ruby里面的self一样难理解。但是对于this的理解,也是能晋升动态语言上一级的前提。
目前阅读coffeescript的书,里面对coffeescript的this做了很不错的总结,我认为完全可以适用于javascript。
0. No doubt some of the confusion stems from the word itself; people expectthisto refer to “this object.” Instead, you should think of it as “this context.”
初学者(指js和coffeescript)容易被this弄糊涂的原因,可能就源之于this的字面意识;大家都以为this指的是“this object“(这个对象)。其实,应该理解为”this context“(当前上下文环境)。1. When the new keyword is put in front of a function call, its context is the new object.
2. When a function is called with callorapply, the context is the first argu- ment given.
3. Otherwise, if a function is called as an object property (obj.func) orobj['func']), it runs in that object’s context.
4. If none of the above apply, then the function runs in the global context.
对于4补充下,如果你没有用new来调用constructor,而是以函数方式来调用,就会出问题,如下例所示:
var Person = function(name){ this.name = name; }
//don't do this
var p = Person('Bob');
你会得到p是undefined, 而且windows多了一个属性name(或者说你多了一个全局变量name,其值是‘Bob')。究其原因,就是作为一般函数调用时,this所指为windows。