DIV CSS 佈局教程網

深入淺談 JavaScript 中的 this 與四種調用模式
編輯:JavaScript綜合知識     

this 是 JavaScript 中最令人困惑的概念之一,特別是在不同的執行上下文裡,它的指向會大不相同。本文從執行上下文出發,系統性地說明四種調用模式下 this 的取值規則,幫助你彻底搞懂 this。

this 的本質

在多數物件導向語言中,this 主要用於指向當前調用的物件。但在 JavaScript 中,this 的行為有明顯差異。事實上,this 是執行上下文(ExecutionContext)裡的一個屬性,因此可以把它理解為:

activeExecutionContext = {
  VO: {...},
  this: thisValue
};

關鍵在於:this 的值取決於函式「如何被調用」,而非它「在哪裡被定義」。JavaScript 共有四種調用模式。

一、方法調用模式

當函式作為某個物件的屬性被調用時,this 會綁定到該物件:

var myObject = {
  value: 0,
  increment: function(inc){
    this.value += typeof inc === "number" ? inc : 1;
  }
};
myObject.increment(); console.log(myObject.value); // 1
myObject.increment(3); console.log(myObject.value); // 4

由於 this 指向所屬物件,因此能透過它存取與修改物件的屬性。這種綁定發生在「調用時」而非「定義時」,稱為延遲綁定,也正是 this 能被高度重複利用的原因:

function showValue(){ console.log(this.value); }
var a = { value: "a" };
var b = { value: "b" };
a.showValue = showValue;
b.showValue = showValue;
a.showValue(); // "a"
b.showValue(); // "b"

二、函數調用模式

當函式並非作為物件方法,而是直接呼叫時,this 會被綁定到全域物件。這被視為語言設計上的一個缺陷,也是許多 bug 的來源:

myObject.double = function(){
  var that = this; // 常見解法
  var helper = function(){
    console.log(that.value); // 正確取得 myObject 的值
    console.log(this.value); // undefined,this 指向了全域物件
  };
  helper();
}

依直覺,helper 內的 this 應該指向所屬物件,但實際上卻指向了全域物件。實務上最簡單的解法,就是在進入內層函式前,先用一個 that 變數保存外層的 this,之後在內層使用 that 代替 this。

三、構造器調用模式

透過 new 搭配構造函式建立物件時,this 會指向新建立的物件:

function Person(name, age){
  this.name = name;
  this.age = age;
  this.say = function(){ console.log("name : %s, age : %n", this.name, this.age); }
}
var p1 = new Person("jink", 24); p1.say(); // name : jink, age : 24
var p2 = new Person("張三", 33); p2.say(); // name : 張三, age : 33

原因在于:以 new 調用函式時,會先觸發內部的 [[Construct]] 建立物件,再透過 [[Call]] 執行函式本體,此時 this 便被設為新建立的物件。值得一提的是,JavaScript 基於原型繼承,其原型機制已足以實踐物件導向所需的繼承與多型,未必需要模仿傳統語言的 new 建構方式。

四、apply 調用模式

所有函式都自帶 apply 與 call 方法,可用來手動指定 this 的指向。apply 的第一個參數,就是函式執行時 this 所指向的物件。這讓我們能「借用」其他物件的方法:

var programmer = {
  name: "程序員", hand: "靈活的雙手",
  programme: function(){ console.log(this.name+"用"+this.hand+"編寫代碼。"); }
};
var pianist = {
  name: "鋼琴家", hand: "靈活的雙手",
  play: function(){ console.log(this.name+"用"+this.hand+"彈奏動聽的樂曲。"); }
};
pianist.play.apply(programmer); // 程序員用靈活的雙手彈奏動聽的樂曲。

apply 的第一個參數即決定了 this 的指向,因此能把 pianist 的 play 方法套用到 programmer 身上。這類技巧在許多框架與程式庫中被廣泛運用。

總結

一句話記法:this 指向誰,取決於「怎麼調用」。作為物件方法調用時指向該物件;單純函式調用時指向全域物件(可用 that 繞過);以 new 調用時指向新物件;透過 apply/call 調用時則指向你指定的物件。理解這四種模式,就能準確預測並掌控 this 的行為,這是精通 JavaScript 的重要一步。

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