DIV CSS 佈局教程網

一段程式碼說清 JavaScript 中 this 的決定規則
編輯:JavaScript基礎知識     

朋友拿這段程式碼來問結果為什麼不如預期:

var name = "The Window";
var object = {
    name: "My Object",
    getNameFunc: function(){
        return function(){
            return this.name;
        };
    }
};

alert(object.getNameFunc()());

答案是 The Window,而不是 My Object。

關鍵:this 由呼叫方式決定

JavaScript 的 this 不是靜態綁定的,而是在執行期依「怎麼呼叫」來決定。規則很簡單:

以 物件.函式名() 的形式呼叫時,this 就是點之前的那個物件;否則 this 為全域物件(在瀏覽器中是 window,在嚴格模式或 ES module 中則是 undefined)。

所以 object.getNameFunc() 裡的 this 確實是 object。但這不代表什麼——因為 getNameFunc 函式體根本沒用到 this,它只是回傳了一個函式。

回傳的函式怎麼被呼叫

外層的那對括號把回傳的函式執行起來,而這個執行形式是「裸呼叫」,前面沒有 物件.。等價的展開寫法如下:

var func = object.getNameFunc();   // 取得回傳的函式
alert(func());                     // 裸呼叫,this 為 window

於是內層的 this.name 讀到的是 window.name,也就是全域的 The Window。

對照:換個呼叫方式就不同

var func = object.getNameFunc;
func();     // getNameFunc 內的 this 變成 window

同一個函式,僅僅因為呼叫方式不同,this 就完全不一樣。

如果想拿到 object 怎麼辦

// 方法一:用閉包捕捉外層的 this
getNameFunc: function(){
    var self = this;
    return function(){ return self.name; };
}

// 方法二:用 bind 固定 this
getNameFunc: function(){
    return (function(){ return this.name; }).bind(this);
}

// 方法三(ES6):箭頭函式不建立自己的 this
getNameFunc: function(){
    return () => this.name;
}

理解這件事的關鍵是:this 與函式在哪裡定義無關,只與它怎麼被呼叫有關。箭頭函式之所以好用,正是因為它沒有自己的 this,會直接沿用外層定義時的那一個。

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