DIV CSS 佈局教程網

JavaScript 中 this 關鍵字詳解:指向規則與實戰陷阱
編輯:關於JavaScript     

學習任何知識時,把它整理成一份清單,往往比零散閱讀更能理清思路。這篇文章就用這樣的方式,把 this 的涵義、使用場合與常見陷阱分層拆解。

本文涵蓋:

  1. 涵義:this 是什麼、指向為何可變
  2. 使用場合:全域環境、建構函式、物件方法
  3. 注意事項:多層嵌套、陣列方法、回呼函式

一、涵義

1.1 this 究竟是什麼

先建立一個基本認知:與 new 關鍵字一樣,this 永遠指向一個物件。更具體地說,它是函式中的屬性或方法「當前所處」的那個物件。

var Keith = {
    firstName: 'Chou',
    describe: function() { return this.firstName; }
};
console.log(Keith.describe()); // 'Chou'

這段程式碼中,this.firstName 指的就是 describe 方法當前所屬物件的 firstName 屬性。因為在全域作用域下呼叫 describe 時,該方法所處的物件是 Keith,所以 this.firstName 等價於 Keith.firstName。

1.2 this 的指向是可變的

由於物件的屬性可以被賦值給另一個物件,屬性所處的「當前物件」自然也會改變,this 的指向因此是動態的。

var Keith = { firstName: 'Chou', describe: function() { return this.firstName; } };
var Rascal = { firstName: 'King' };
Rascal.describe = Keith.describe;
console.log(Rascal.describe()); // 'King'

把 Keith 的 describe 屬性賦值給 Rascal 之後,describe 方法當前所屬的物件變成了 Rascal,於是 this.firstName 指向 Rascal。注意這裡是傳址,修改會影響原物件。

把方法抽到全域作用域,差異會更明顯:

function f(){ return this.firstName; }
var Keith  = { firstName: 'Chou', describe: f };
var Rascal = { firstName: 'King', describe: f };
console.log(Keith.describe());  // 'Chou'
console.log(Rascal.describe()); // 'King'

同一個函式 f,隨著所處物件不同,this 的指向也不同。這正是 this 最容易讓人栽跟頭的地方。

而在全域作用域中,this 指向最頂層的物件,也就是 window:

var name = 'keith';
function person(){ var name = 'rascal'; return this.name; }
console.log(person()); // 'keith'

回傳的是 keith 而不是 rascal,因為 this 指向全域作用域。在全域定義的函式預設指向 window 物件,而不是函式本身。

不過,如果函式內部沒有用 var 宣告區域變數,結果就不同了:

var name = 'keith';
function person(){ name = 'rascal'; return this.name; }
console.log(person()); // 'rascal'

此時函式內部的 name 不是區域變數,而是全域變數,於是覆寫掉了原本的 name。這是區域變數與全域變數作用域差異的直接後果。

另外,只要函式被賦值給另一個變數,this 的指向就會改變:

var Keith = { name: 'keith', describe: function(){ return this.name; } };
var name = 'rascal';
var f = Keith.describe;
console.log(f()); // 'rascal'

回傳 rascal 而非 keith,因為 Keith.describe 被賦值給 f 之後,this 指向的是 f 執行時所處的物件,也就是 window。

小結:

  1. JavaScript 中除了 undefined 與 null,一切都是物件,執行環境本身也是物件。函式都在某個物件之中執行,this 就是那個環境。
  2. this 的指向是動態的:函式在全域作用域中,this 指向全域環境;函式屬於某個物件,this 指向該物件。

二、三種主要使用場合

2.1 全域環境

在全域作用域中使用 this,它指向最頂層的 window 物件。

function keith() { return (this === window); }
console.log(keith()); // true

2.2 建構函式

建構函式中的 this,指向即將被建立的物件實例。

function Keith() { this.sex = 'boy'; }
var person = new Keith();
console.log(person.sex); // 'boy'

建構函式的三個基本要件:函式名首字母大寫;內部用 this 指向即將產生的實例;用 new 呼叫並回傳實例。

2.3 物件的方法

當 A 物件的方法被賦予 B 物件,該方法中的 this 就從 A 變成 B。這是必須特別小心的地方。

var keith  = { sex: 'boy',  foo: function() { return this.sex; } };
var rascal = { sex: 'girl' };
rascal.foo = keith.foo;
console.log(keith.foo());  // 'boy'
console.log(rascal.foo()); // 'girl'

如果方法位於多層物件內部,為了精簡寫法而把它賦值給變數,往往會得到非預期的結果:

var a = { b: { p: 'keith', c: function() { return this.p; } } };
var person = a.b.c;
console.log(person()); // undefined

c 是兩層物件中的方法,賦值給全域變數 person 之後,this 指向 window,而 window 上並沒有 p,於是回傳 undefined。解法有兩個:只把 c 所屬的物件賦值給變數,或者直接呼叫。

var person = a.b;
console.log(person.c()); // 'keith'
console.log(a.b.c());    // 'keith'

三、實戰中的三個陷阱

3.1 避免多層 this 嵌套

在閉包中使用多層 this,內層的 this 會指向 window:

function keith() {
    console.log(this);
    return function() { return this; }
}
keith();   // window
keith()(); // window

如果函式外層包著一個物件,則內層 this 指向全域,外層 this 指向當前物件:

var o = { f1: function() {
    console.log(this);
    (function() { console.log(this) })();
} };
o.f1(); // Object, Window

要實現多層 this 嵌套,有兩種解法。

解法一:用一個變數固定外層的 this。

var o = { f1: function() {
    console.log(this);
    var that = this;
    (function() { console.log(that); })();
} };
o.f1(); // Object, Object

解法二:使用嚴格模式。嚴格模式下若 this 指向 window,會直接報錯而非靜默失敗:

var a = { count: 0, fun: function() {
    'use strict';
    return this.count++;
} };
var f = a.fun;
console.log(f()); // TypeError: this is undefined

3.2 避免陣列處理方法中的 this

map 與 forEach 允許傳入一個函式作為參數,但這個函式內部不應該使用 this。

var keith = { a: 'Hello', b: ['b1', 'b2'], c: function() {
    this.b.forEach(function(item) {
        console.log(this.a + ' ' + item);
    })
} };
keith.c(); // undefined b1 / undefined b2

forEach 回呼函式中的 this 指向 window,取不到 keith.a。這本質上仍是多層 this 問題:內層的 this 不指向外層函式,而是指向頂層物件。

解法一,用 that 變數承接:

var keith = { a: 'Hello', b: ['b1', 'b2'], c: function() {
    var that = this;
    this.b.forEach(function(item) { console.log(that.a + ' ' + item); })
} };
keith.c(); // Hello b1 / Hello b2

解法二,把 this 作為 forEach 的第二個參數傳入,固定執行環境:

var keith = { a: 'Hello', b: ['b1', 'b2'], c: function() {
    this.b.forEach(function(item) {
        console.log(this.a + ' ' + item);
    }, this)
} };
keith.c(); // Hello b1 / Hello b2

3.3 避免回呼函式中的 this

回呼函式中的 this 往往會改變指向:

var o = { f: function() { console.log(this === o); } };
o.f(); // true

直接呼叫時回傳 true。但一旦把它綁到按鈕的 click 事件上,指向就變了:

$('button').on('click', o.f);

點擊後主控台顯示 false。原因是此時 this 不再指向 o,而是指向該按鈕的 DOM 物件——因為 f 是在按鈕物件的環境中被呼叫的。

總結:

  1. 需要多層 this 時,最實用的做法是宣告 that 變數固定外層 this,內層改用 that,就不會出現內層 this 指向全域的問題。
  2. 在回呼函式中使用 this 時,務必先確認它的實際指向是什麼。

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