JavaScript 的 this 和 Java 等物件導向語言中的 this 差得很遠,而 bind()、call()、apply() 更是把它的靈活度推向另一個層次。如果對 this 理解不夠透,很容易掉進意料之外的坑裡。
先記住一個前提:this 的值由函數的執行環境決定,也就是要看「函數是怎麼被呼叫的」,而不是「在哪裡定義」。同一個函數每次呼叫,this 都可能指向不同物件。以下五條規則涵蓋了日常絕大多數情況。
打開 Chrome 開發者面板(Windows: Ctrl + Shift + J/Mac: Cmd + Option + J),輸入:
console.log(this);
你會看到:
// Window {}
是 window 物件。因為在全域作用域下,this 指向全域物件,而在瀏覽器中全域物件就是 window。
再看一個例子:
var myName = 'Brandon';
在控制台輸入 myName 可以取到值:
myName // 'Brandon'
其實所有在全域定義的變數都綁定在 window 上:
window.myName // 'Brandon' window.myName === myName // true
把 this 放進函數內部也是一樣:
function test() {
return this;
}
test();
this 依然指向全域 window。因為它並不處於任何宣告物件的內部,預設就落在全域物件上。注意:在嚴格模式(strict mode)下,這裡的 this 會是 undefined。
當 this 出現在物件內的方法中,它的值會綁定到「呼叫該函數的最近一層父物件」。
var person = {
first: 'John',
last: 'Smith',
full: function () {
console.log(this.first + ' ' + this.last);
}
};
person.full(); // 'John Smith'
full 裡用了 this,而呼叫它的父物件是 person,所以 this 指向 person。把 this 直接印出來更直觀:
var person = {
first: 'John',
last: 'Smith',
full: function () {
console.log(this);
}
};
person.full(); // Object {first: "John", last: "Smith", full: function}
來看更複雜的嵌套情況:
var person = {
first: 'John',
last: 'Smith',
full: function () {
console.log(this.first + ' ' + this.last);
},
personTwo: {
first: 'Allison',
last: 'Jones',
full: function () {
console.log(this.first + ' ' + this.last);
}
}
};
此時 this 分別指向誰?
person.full(); // 'John Smith' person.personTwo.full(); // 'Allison Jones'
完全符合規則:綁定到呼叫它的最近一層父物件。
用 new 建構新物件時,this 會綁定到這個新物件。
function Car(make, model) {
this.make = make;
this.model = model;
};
照規則一你可能會猜 this 指向全域,但只要用 new 呼叫,this 就會綁定到一個新建的空物件,再初始化 make 與 model:
var myCar = new Car('Ford', 'Escape');
console.log(myCar); // Car {make: "Ford", model: "Escape"}
這三個方法可以讓我們顯式指定 this 的綁定對象。它們很像,但差別在細節。
先看 call 與 apply:
function add(c, d) {
console.log(this.a + this.b + c + d);
}
add(3, 4); // NaN
輸出 NaN,因為 this.a 與 this.b 都未定義。現在引入一個物件並改用 call/apply:
function add(c, d) {
console.log(this.a + this.b + c + d);
}
var ten = { a: 1, b: 2 };
add.call(ten, 3, 4); // 10
add.apply(ten, [3, 4]); // 10
call 的第一個參數是 this 要綁定的物件,其後依序是函數本身的參數;apply 唯一的差別是第二個參數必須用陣列包裝。
bind() 與 call() 類似,但不會立即執行,而是回傳一個已綁定好 this 的新函數。看個應用場景:
var small = {
a: 1,
go: function (b, c, d) {
console.log(this.a + b + c + d);
}
}
var large = { a: 100 }
正常呼叫:
small.go(2, 3, 4); // 10
如果想用 large.a,可以用 call/apply:
small.go.call(large, 2, 3, 4); // 109
但如果參數值此時還不知道呢?用 bind:
var bindTest = small.go.bind(large, 2);
印出來會看到:
console.log(bindTest); // function (b,c,d){console.log(this.a+b+c+d);}
這個函數已經把 this 綁定到 large,並預先填入第一個參數,接著只要補上剩下的即可:
bindTest(3, 4); // 109
箭頭函數不會綁定 this,它會沿用外層作用域的 this。這點差異非常關鍵,值得單獨用一篇文章說明。
複習一下這五條:
· this 的值由函數的呼叫方式決定;
· 在全域作用域,this 指向全域物件(瀏覽器中的 window);
· 使用 new 呼叫時,this 指向新建的物件;
· 可以用 call()、bind()、apply() 顯式指定 this;
· 箭頭函數不綁定 this。
把這五條記牢,日常開發中九成的 this 問題都能即時判斷出來。
原文:JavaScript: The Keyword 'This' for Beginners
譯者:Fundebug