DIV CSS 佈局教程網

JavaScript 的 this 反柯里化(Uncurrying this)完整解析
編輯:關於JavaScript     

這個話題源自 Brendan Eich(JavaScript 之父)的一則 tweet,核心是把方法的呼叫形式做一次轉換。

什麼是反柯里化 this

反柯里化的目標,是把這種簽名的方法:

obj.foo(arg1, arg2)

變成這種形式的獨立函式:

foo(obj, arg1, arg2)

要理解它為什麼有用,得先認識「通用方法」。

通用方法(Generic methods)

一般來說,某個方法只能用在特定型別的物件上。但有些方法如果能跨型別使用,會方便很多:

// 簡化後的實作
Array.prototype.forEach = function (callback) {
    for (var i = 0; i < this.length; i++) {
        if (i in this) {
            callback(this[i], i);
        }
    }
};

這裡的 this 是 forEach 的隱含參數。任何滿足以下三個條件的物件,都能當這個 this 使用:

  • 具備 length 屬性:this.length
  • 能用索引取值:this[i]
  • 能檢查屬性是否存在:i in this

arguments 物件不是 Array 的實例,所以不能「直接」呼叫 forEach,但它完全符合上述三個條件。解法就是把隱含的 this 變成顯式參數——每個函式都有的 call() 正是為此而生:

function printArgs() {
    Array.prototype.forEach.call(arguments, function (elem, index) {
        console.log(index + ". " + elem);
    });
}

forEach.call() 比 forEach() 多帶一個參數,也就是要指定的 this 值:

> printArgs("a", "b")
0. a
1. b

JavaScript 中還有幾個同類的通用方法,大多來自 Array.prototype。

反柯里化的實際用途

用途一:搭配 map() 呼叫方法。map 的 callback 是函式,若你想對每個元素呼叫某個「方法」,反柯里化就能派上用場:

> var toUpperCase = String.prototype.toUpperCase.uncurryThis();
> [ "foo", "bar", "baz" ].map(toUpperCase)
[ 'FOO', 'BAR', 'BAZ' ]

用途二:把通用方法變成好用的函式。

Array.forEach = Array.prototype.forEach.uncurryThis();
function printArgs() {
    Array.forEach(arguments, function (elem, index) {
        console.log(index + ". " + elem);
    });
}

當時的 ECMAScript 規範草案已納入不少這類陣列方法,Firefox 也早就實作了 Array.map、Array.forEach 等。

uncurryThis() 的三種實作

Brendan Eich 的版本:

Function.prototype.uncurryThis = function () {
    var f = this;
    return function () {
        var a = arguments;
        return f.apply(a[0], [].slice.call(a, 1));
    };
};

第二種思路是:反柯里化後的函式,效果等同於對原方法呼叫 call(),因此把 call() 用 bind() 借過來即可:

Function.prototype.uncurryThis = function () {
    return this.call.bind(this);
};

第三種則避免依賴過多外部方法(bind() 只在 ES5 才有):

Function.prototype.uncurryThis = function () {
    var f = this;
    return function () {
        return f.call.apply(f, arguments);
    };
};

反向操作:柯里化 this

uncurryThis() 的反向操作是 curryThis(),它會把函式的第一個參數轉為隱含的 this。原本的函式:

function (self, arg) {
    return self.foo + arg;
}

柯里化之後變成:

function (arg) {
    return this.foo + arg;
}

典型場景是讓方法把自己的 this 帶進巢狀函式。原本得靠 self 這種中繼變數:

var obj = {
    method: function (arg) {
        var self = this;   // 讓巢狀函式拿得到 this
        someFunction(..., function () {
            self.otherMethod(arg);
        });
    },
    otherMethod: function (arg) { ... }
};

柯里化之後可以這樣寫:

var obj = {
    method: function (self, arg) {   // 多了 self 參數
        someFunction(..., function () {
            self.otherMethod(arg);
        });
    }.curryThis(),
    otherMethod: function (arg) { ... }
};

本質上,我們把動態的 this 換成了靜態的變數 self。如果 this 一律以顯式參數存在,JavaScript 會單純不少。

Function.prototype.curryThis = function () {
    var f = this;
    return function () {
        var a = Array.prototype.slice.call(arguments);
        a.unshift(this);
        return f.apply(null, a);
    };
};

不想擴充 Function 原型?

上面都掛在內建的 Function.prototype 上,其實很容易改寫成獨立函式:

function uncurryThis(f) {
    return function () {
        return f.call.apply(f, arguments);
    };
}
function curryThis(f) {
    return function () {
        var a = Array.prototype.slice.call(arguments);
        a.unshift(this);
        return f.apply(null, a);
    };
}

Mark Miller 曾以 uncurryThis() 為例講解「安全的元程式設計(safe metaprogramming)」,說明如何在充斥不受信任程式碼的環境中安全地使用它。

一句話記法:柯里化 this 是把函式的第一個參數變成方法裡的 this;反柯里化 this 則是把方法裡的 this 變成函式的第一個參數。

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