2011年3月12日星期六

javascript中的this关键字

下面这段是从jQuery Fundamental中copy过来的。
The this keyword

In JavaScript, as in most object-oriented programming languages, this is a special keyword that is used within methods to refer to the object on which a method is being invoked. The value of this is determined using a simple series of steps:

1. If the function is invoked using Function.call or Function.apply, this will be set to the first argument passed to call/apply. If the first argument passed to call/apply is null or undefined, this will refer to the global object (which is the window object in Web browsers).
2. If the function being invoked was created using Function.bind, this will be the first argument that was passed to bind at the time the function was created.
3. If the function is being invoked as a method of an object, this will refer to that object.
4. Otherwise, the function is being invoked as a standalone function not attached to any object, and this will refer to the global object.

我觉得比较好的解释了this的意义。其中第三和第四是经常碰到的情况。其实它还漏了一种经常发生的情况情况,那就是constructor function中this的意思。对于constructor function,this代表new出来的对象,一开始是空,最后返回给调用者。看例子吧:

// For constructor function, 
// you could add the first and the last line, 
// or browser will add them for you defaultly.
foo = function(x){
   // this = {}; 
   this.x = x; 
   // return this; 
}; 

bar = new foo(); 

没有评论: