JavaScript 的 this 介紹

在JavaScript中,函式的this關鍵字的行為與其他語言相比有很多不同。在JavaScript的嚴格模式和非嚴格模式下也略有區別。

在絕大多數情況下,函式的呼叫方式決定了this的值。this不能在執行期間被賦值,在每次函式被呼叫時this的值也可能會不同。ES5引入了bind方法來設置函式的this值,而不用考慮函式如何被呼叫的。
全域上下文

在全域執行上下文中(在任何函式體外部),this 指代全域物件,無論是否在嚴格模式下。

console.log(this.document === document); // true

// 在瀏覽器中,全域物件為 window 物件:
console.log(this === window); // true

this.a = 37;
console.log(window.a); // 37

函式上下文

在函式內部,this的值取決於函式是如何呼叫的。
直接呼叫

function f1(){
  return this;
}

f1() === window; // true

在上面的例子中,this的值不是由函式呼叫設定。因為程式碼不是在嚴格模式下執行,this 的值總是一個物件且預設為全域物件。

function f2(){
  "use strict"; // 這裡是嚴格模式
  return this;
}

f2() === undefined; // true

在嚴格模式下,this 是在進入執行環境時設置的。若沒有定義,this的值將維持undefined狀態。同時它也能設置成任意值,比如 null 或者42 或者「I am not this」。
注意:在第二個例子中,this應該是undefined。因為f2不是作為方法呼叫的(見下文)。這個功能並未在所有第一次開始支持嚴格模式的瀏覽器中都得到了實現。因此有些瀏覽器返回了錯誤的結果 :window 物件。
物件方法中的 this

當以物件裡的方法的方式呼叫函式時,它們的 this 是呼叫該函式的物件.

下面的例子中,當 o.f() 被呼叫時,函式內的this將綁定到o物件。

var o = {
  prop: 37,
  f: function() {
    return this.prop;
  }
};

console.log(o.f()); // logs 37

注意,在何處或者如何定義呼叫函式完全不會影響到this的行為。在上一個例子中,我們在定義o的時候為其成員f定義了一個匿名函式。但是,我們也可以首先定義函式然後再將其附屬到o.f。這樣做this的行為也一致:

var o = {prop: 37};

function independent() {
  return this.prop;
}

o.f = independent;

console.log(o.f()); // logs 37

這說明this的值只與函式 f 作為 o 的成員被呼叫有關係。

類似的,this 的綁定只受最靠近的成員引用的影響。在下面的這個例子中,我們把一個方法g當作物件o.b的函式呼叫。在這次執行期間,函式中的this將指向o.b。事實上,這與物件本身的成員沒有多大關係,最靠近的引用才是最重要的。

o.b = {
  g: independent,
  prop: 42
};
console.log(o.b.g()); // logs 42

原型鏈中的 this

相同的概念在定義在原型鏈中的方法也是一致的。如果該方法存在於一個物件的原型鏈上,那麼this指向的是呼叫這個方法的物件,表現得好像是這個方法就存在於這個物件上一樣。

var o = {
  f : function(){
    return this.a + this.b;
  }
};
var p = Object.create(o);
p.a = 1;
p.b = 4;

console.log(p.f()); // 5

在這個例子中,物件p沒有屬於它自己的f屬性,它的f屬性繼承自它的原型。但是這對於最終在o中找到f屬性的查找過程來說沒有關係;查找過程首先從p.f的引用開始,所以函式中的this指向p。也就是說,因為f是作為p的方法呼叫的,所以它的this指向了p。這是JavaScript的原型繼承中的一個有趣的特性。
 getter 與 setter 中的 this

再次,相同的概念也適用時的函式作為一個 getter 或者 一個setter呼叫。作為getter或setter函式都會綁定 this 到從設置屬性或得到屬性的那個物件。

function modulus(){
  return Math.sqrt(this.re * this.re + this.im * this.im);
}

var o = {
  re: 1,
  im: -1,
  get phase(){
    return Math.atan2(this.im, this.re);
  }
};

Object.defineProperty(o, 'modulus', {
  get: modulus, enumerable:true, configurable:true});

console.log(o.phase, o.modulus); // logs -0.78 1.4142

建構式中的 this

當一個函式被作為一個建構式來使用(使用new關鍵字),它的this與即將被新增的新物件綁定。

注意:當構造器返回的預設值是一個this引用的物件時,可以手動設置返回其他的物件,如果返回值不是一個物件,返回this。

/*
 * Constructors work like this:
 *
 * function MyConstructor(){
 *   // Actual function body code goes here. 
 *   // Create properties on |this| as
 *   // desired by assigning to them.  E.g.,
 *   this.fum = "nom";
 *   // et cetera...
 *
 *   // If the function has a return statement that
 *   // returns an object, that object will be the
 *   // result of the |new| expression.  Otherwise,
 *   // the result of the expression is the object
 *   // currently bound to |this|
 *   // (i.e., the common case most usually seen).
 * }
 */

function C(){
  this.a = 37;
}

var o = new C();
console.log(o.a); // logs 37


function C2(){
  this.a = 37;
  return {a:38};
}

o = new C2();
console.log(o.a); // logs 38

在最後的例子中(C2),因為在呼叫建構式的過程總,手動的設置了返回物件,與this綁定的預設物件被取消(本質上這使得語句「this.a = 37;」成了「殭屍」程式碼,實際上並不是真正的「殭屍」,這條語句執行了但是對於外部沒有任何影響,因此完全可以忽略它)。
call 和 apply

當一個函式的函式體中使用了this關鍵字時,通過所有函式都從Function物件的原型中繼承的call()方法和apply()方法呼叫時,它的值可以綁定到一個指定的物件上。

function add(c, d){
  return this.a + this.b + c + d;
}

var o = {a:1, b:3};

// The first parameter is the object to use as 'this', subsequent parameters are passed as
// arguments in the function call
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16

// The first parameter is the object to use as 'this', the second is an array whose
// members are used as the arguments in the function call
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34

使用 call 和 apply 函式的時候要注意,如果傳遞的 this 值不是一個物件,JavaScript 將會嘗試使用內部 ToObject 操作將其轉換為物件。因此,如果傳遞的值是一個原始值比如 7 或 'foo' ,那麼就會使用相關建構式將它轉換為物件,所以原始值 7 通過new Number(7)被轉換為物件,而字串'foo'使用 new String('foo') 轉化為物件,例如:

function bar() {
  console.log(Object.prototype.toString.call(this));
}

bar.call(7); // [object Number]

bind 方法

ECMAScript 5 引入了 Function.prototype.bind。呼叫f.bind(someObject)會新增一個與f具有相同函式體和作用域的函式,但是在這個新函式中,this將永久地被綁定到了bind的第一個參數,無論這個函式是如何被呼叫的。

function f(){
  return this.a;
}

var g = f.bind({a:"azerty"});
console.log(g()); // azerty

var o = {a:37, f:f, g:g};
console.log(o.f(), o.g()); // 37, azerty

DOM事件處理函式中的 this

當函式被用作事件處理函式時,它的this指向觸發事件的元素(一些瀏覽器在動態增加監聽器時不遵守這個約定,除非使用addEventListener 這句不太確定翻譯的是否正確)。

// 被呼叫時,將關聯的元素變成藍色
function bluify(e){
  console.log(this === e.currentTarget); // 總是 true

  // 當 currentTarget 和 target 是同一個物件是為 true
  console.log(this === e.target);       
  this.style.backgroundColor = '#A5D9F3';
}

// 獲取文件中的所有元素的列表
var elements = document.getElementsByTagName('*');

// 將bluify作為元素的點擊監聽函式,當元素被點擊時,就會變成藍色
for(var i=0 ; i<elements.length ; i++){
  elements[i].addEventListener('click', bluify, false);
}

內聯事件處理函式中的 this

當程式碼被內聯處理函式呼叫時,它的this指向監聽器所在的DOM元素:

<button onclick="alert(this.tagName.toLowerCase());">
  Show this
</button>

上面的alert會顯示button。注意只有外層程式碼中的this是這樣設置的:

<button onclick="alert((function(){return this}}()));">
  Show inner this
</button>

在這種情況下,沒有設置內部函式的 this,所以它指向 global/window 物件(即非嚴格模式下呼叫的函式未設置 this 時指向的預設物件)。

留言

這個網誌中的熱門文章

c語言-關於#define用法

PHP教學 - 資料型態(Data Type) - 上

CMD常用網管指令