同一個函式,用不同方式呼叫時 this 的指向完全不同。把函式的存在形態分成四類來看,這件事就清楚多了。
直接呼叫時,非嚴格模式下 this 指向全域物件。
var foo = function () { alert(this); }; // this 是 window
foo();
把函式指派給某個物件的屬性,它就成了該物件的方法,呼叫時 this 指向所屬物件。
var o = {};
o.foo = foo;
o.foo(); // 此時 this 代表 o
容易踩坑的是巢狀結構:
var lib = {
test: function () {
alert(this); // 這裡的 this 是 lib 本身
(function () {
alert(this); // 這個匿名函式不屬於 lib,this 仍是 window
})();
}
};
lib.test();
解法是在進入內層前先存一份 this:
var lib = {
test: function () {
var that = this;
(function () { alert(that); })();
}
};
用 new 呼叫時,引擎依序做三件事:
關鍵補充:若函式明確回傳一個物件,這個回傳值會取代 this;若回傳的是原始值,則被忽略。
var Person = function () {
this.age = 19;
this.name = "Mr靖";
return "{}"; // 回傳物件,age 與 name 被丟棄
};
var p = new Person();
alert(p.name); // undefined
var Person = function () {
this.age = 19;
this.name = "Mr靖";
return 123; // 回傳原始值,被忽略
};
var p = new Person();
alert(p.name); // "Mr靖"
alert(p); // object
差別只有回傳值的型別,但結果完全不同。撰寫建構函式時,最好不要回傳任何值。
apply 與 call 能顯式指定 this。兩者差別只在參數傳遞方式:apply 收陣列,call 逐一列舉。
var foo1 = function (a, b) {
alert(this);
return a > b ? a : b;
};
var num = foo1.apply(null, [112, 34]); // this 為全域,等同函式形態
num = foo1.apply({}, [112, 34]); // this 為傳入的 {},等同方法形態
var num1 = foo1.call(null, 112, 34);
num1 = foo1.call({}, 112, 34); // 除參數寫法外與 apply 相同
理解這四種形態,就能解釋絕大多數 this 相關的疑問。實務上若要綁定 this 而不想每次呼叫都指定,可用 bind() 事先固化;ES6 的箭頭函式則直接沿用外層 this,是另一種思路。