DIV CSS 佈局教程網

JavaScript 中 this 的六條歸屬規則
編輯:關於JavaScript     

this 大概是 JavaScript 裡最容易讓人栽跟頭的關鍵字。麻煩之處在於它不是「詞法作用域」決定的,而是由呼叫方式決定——同一個函式,不同呼叫寫法下的 this 完全不同。從 C++ 或 Python 帶過來的 self 直覺,往往正是誤解的來源。

規則一:全域環境中的 this

JavaScript 的作用域由函式界定,用 if、for 這類區塊並不會隔出新的 this 上下文。因此不屬於任何函式的頂層環境就是全域環境,此時 this 指向全域物件(瀏覽器中的 window)。

var name = 'jjj';
console.log(this.name);   // jjj

在 ES Module 或嚴格模式下,頂層 this 是 undefined,這是另一個必須留意的差異。

規則二:作為方法呼叫

寫成 物件.方法() 的形式時,this 指向該物件,這與 Python 的 self 最接近。

var user = { name: 'kkk' };
user.getName = function() {
  console.log(this.name);
};
user.getName();     // kkk

規則三:作為建構函式

用 new 呼叫時,this 指向新建立的物件。順帶釐清一個常見誤解:物件其實在函式執行前就已被建立,建構函式的工作只是初始化。

function User(name) { this.name = name; }
var f1 = new User('kkk');
var f2 = User('kkk');          // 忘記 new
console.log(f1.name);          // kkk
console.log(f2.name);          // undefined(在非嚴格模式下反而會汙染全域)

規則四:間接呼叫(call / apply / bind)

用 call 或 apply 呼叫時,this 由第一個參數明確指定。

function setName(name) { this.name = name; }
var user = { level: 2 };
setName.call(user, 'jjj');
console.log(user.name);        // jjj

範例中常見的 user.apply(setName, 'jjj') 是寫錯的,正確用法是 setName.apply(user, ['jjj'])。順帶一提,bind 會回傳一個 this 被永久綁定的新函式。

規則五:其他情況——this 不會被「繼承」

這是最容易出錯的地方:巢狀函式中的 this 不會指向包覆它的函式。

var name = "clever coder";
var person = {
  name: "foocoder",
  hello: function(sth) {
    var sayhello = function(sth) {
      console.log(this.name + " says " + sth);
    };
    sayhello(sth);
  }
};
person.hello("hello world");   // clever coder says hello world

看起來很反直覺:明明在 person 的方法裡,為什麼 this 不是 person?因為 sayhello 是以「純函式呼叫」的方式被觸發的,與 person 沒有任何關係,this 於是回到全域物件。若把 log 直接寫在 hello 內,就會正確輸出 foocoder。

補充一個細節:在 Node.js 環境下,模組頂層的 this 指向 module.exports 而非全域物件,所以同樣的程式碼會輸出 undefined says hello world。

傳統解法是把 this 存進一個變數再用:

var self = this;      // 或使用 arrow function 直接繼承外層 this

規則六:箭頭函式改寫了規則

ES6 的箭頭函式沒有自己的 this,它會沿用定義所在位置的 this。上面那個例子若改成箭頭函式,就會如實輸出 foocoder:

hello: function(sth) {
  var sayhello = (s) => console.log(this.name + " says " + s);
  sayhello(sth);
}

這也是為什麼箭頭函式不適合當方法或建構函式——它無法動態取得呼叫者,也不能用 new。反之,回呼函式(事件處理除外)、Promise 鏈、集合的迭代方法,用箭頭函式幾乎總是對的。

一句話總結

判斷 this 時,只看「這個函式是怎麼被呼叫的」:有沒有 new、是不是物件的方法、有沒有被 call/apply/bind 指定、是不是箭頭函式。依序檢查這四點,絕大多數情況都能立刻得出答案。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved