JavaScript 的 this 之所以讓人頭痛,是因為它在運行期才被綁定,同一個 this 在不同呼叫方式下指向完全不同的東西。但只要掌握四種呼叫模式,一切就清晰了。
obj.a()a()new a()window.a = 2;
var obj = {
a: 1,
getA: function () { console.log(this.a); }
};
obj.getA(); // 輸出 1,作為物件方法,this 指向 obj
var x = obj.getA;
x(); // 輸出 2,作為普通函數,this 指向 window
關鍵規則:無論 x 之前是誰的屬性,只要最後是以 x()、fun() 這種「裸呼叫」形式執行,就視為普通函數呼叫,this 指向 window。
但在 ES5 的 strict mode 下,普通函數呼叫的 this 不再指向全域物件,而是 undefined:
window.a = 2;
var obj = {
a: 1,
getA: function () {
"use strict"
console.log(this.a);
}
};
var x = obj.getA;
x(); // undefined
用 new 呼叫時,this 通常指向新建立的物件。但有個例外:如果建構函數顯式 return 了一個物件,那 this 就指向那個回傳的物件。
var MyClass = function () {
this.name = 'beidan';
};
var obj = new MyClass();
console.log(obj.name); // "beidan"
var MyClass2 = function () {
this.name = 'beidan';
return { // 顯式回傳物件,name 被覆蓋
name: 'test'
};
};
var obj2 = new MyClass2();
console.log(obj2.name); // "test"
注意兩個條件必須同時成立:一是有 return,二是回傳的是物件型別。若回傳的是基本型別,則會被忽略。
兩者的作用完全相同——改變函數體內部 this 的指向,差別只在參數的傳遞形式:
func1.call(this, arg1, arg2); // 參數逐一列出 func1.apply(this, [arg1, arg2]); // 參數放進陣列
第一個參數決定函數體內 this 的指向,可以是任何 JavaScript 物件;若傳 null,this 會退回預設的宿主物件(瀏覽器中為 window)。當參數數量不確定時用 apply,把參數 push 進陣列再傳入即可,也可以直接用 arguments。
document.getElementById('div1').onclick = function () {
console.log(this.id); // "div1"
var func = function () {
console.log(this.id);
};
func(); // undefined,普通函數呼叫指向 window
func.call(this); // "div1",用 call 把 this 拉回外層函數
};
function Fruits() {}
Fruits.prototype = {
color: "red",
say: function () { console.log("My color is " + this.color); }
};
var apple = new Fruits();
apple.say(); // "My color is red"
var banana = { color: "yellow" };
var orange = { color: "orange" };
apple.say.call(banana); // "My color is yellow"
apple.say.apply(orange); // "My color is orange"
也就是說,當某個物件缺少某方法(banana 沒有 say),而另一個物件有(apple 有 say),就可以透過 call / apply 借用。這正是「模擬繼承」的基礎。
var numbers = [5, 458, 120, -215]; var maxInNumbers = Math.max.apply(Math, numbers); // 458 var maxNumbers = Math.max.call(Math, 5, 458, 120, -215, 666); // 666
Math.max 本身不接受陣列,但 numbers 沒有 max 方法,Math 有——apply 剛好把陣列攤平成參數列表,完美解決。
掌握這四條,加上箭頭函數「this 繼承自外層作用域」這條 ES6 規則,實務上的 this 問題基本都能應對。