DIV CSS 佈局教程網

用 bind 與閉包鎖定函數的執行上下文
編輯:關於JavaScript     

把物件的方法指派給另一個變數之後,this 往往就跑到別的地方去了。這是 JavaScript 裡最經典的坑之一,而 bind 就是為了解決它而生的。

問題重現

window.name = "the window object"

function scopeTest() {
    return this.name;
}

// calling the function in global scope:
scopeTest()
// -> "the window object"

var foo = {
    name: "the foo object!",
    otherScopeTest: function() { return this.name }
};

foo.otherScopeTest();   // -> "the foo object!"

var foo_otherScopeTest = foo.otherScopeTest;
foo_otherScopeTest();
// –> "the window object"

直接呼叫 foo.otherScopeTest() 時,this 是 foo,一切正常。但一旦把方法取出來單獨賦值給變數再呼叫,this 就退回到全域對象了。原因是 this 由「呼叫方式」決定,而不是由「定義位置」決定。

如果你希望一個函數被轉移到別的變數之後,執行上下文仍然黏在原物件上,就需要 bind。

Prototype.js 的實作

// The .bind method from Prototype.js
Function.prototype.bind = function() {
    var fn = this,
        args = Array.prototype.slice.call(arguments),
        object = args.shift();
    return function() {
        return fn.apply(object,
            args.concat(Array.prototype.slice.call(arguments)));
    };
};

邏輯很清楚:把 arguments 轉成真陣列,取出第一個參數作為要綁定的對象,剩下的存成預設參數;回傳的新函數被呼叫時,用 apply 把 this 固定住,並把「預設參數」與「當次傳入的參數」拼接起來一起送進去。

使用示範

var obj = {
    name: 'A nice demo',
    fx: function() {
        alert(this.name);
    }
};

window.name = 'I am such a beautiful window!';

function runFx(f) {
    f();
}

var fx2 = obj.fx.bind(obj);

runFx(obj.fx);  // alert: I am such a beautiful window!
runFx(fx2);     // alert: A nice demo

runFx 是個典型的「把函數當參數傳遞」的場景——像是 setTimeout、事件回調、陣列迭代都屬於這類。沒有 bind 時 this 會丟失,加上 bind 之後就穩穩指向 obj。

自己寫一個簡化版

Function.prototype.bind = function(obj) {
    var _this = this;
    return function() {
        return _this.apply(obj, Array.prototype.slice.call(arguments));
    }
}

var name = 'window',
    foo = {
        name: 'foo object',
        show: function() { return this.name; }
    };

console.assert(foo.show() == 'foo object',
    'expected foo object, actual is ' + foo.show());

var foo_show = foo.show;
console.assert(foo_show() == 'window',
    'expected is window, actual is ' + foo_show());

var foo_show_bind = foo.show.bind(foo);
console.assert(foo_show_bind() == 'foo object',
    'expected is foo object, actual is ' + foo_show_bind());

這個版本更精簡,用閉包把 _this 保存下來,回傳的函數透過 apply 永遠以 obj 作為 this。三個 console.assert 剛好對應三種情況:正常呼叫、上下文丟失、bind 之後修復。

它與 Prototype 版本的差別在於:簡化版沒有處理「部分參數預綁」的功能,也就是不支援 bind(obj, 1, 2) 這種柯里化寫法。若要完整對齊原生行為,就得把 Prototype 那版的 args.concat(...) 加回來。

補充

ES5 已經內建 Function.prototype.bind,現代專案直接用即可。不過要記住 bind 有三個特性:綁定後的 this 無法再被改寫(再用 call 或 apply 也沒用)、它會回傳一個新函數而非修改原函數、以及不支援柯里化以外的 new 操作(實際上 bind 後的函數仍可用 new,但 this 會被忽略)。理解這些細節,才能在除錯時快速定位問題。

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