如何在JavaScript中部分应用成员函数?

bfo*_*ops 6 javascript currying partial-application

我目前有一个部分应用程序功能,如下所示:

Function.prototype.curry = function()
{
    var args = [];
    for(var i = 0; i < arguments.length; ++i)
        args.push(arguments[i]);

    return function()
    {
        for(var i = 0; i < arguments.length; ++i)
            args.push(arguments[i]);

        this.apply(window, args);
    }.bind(this);
}
Run Code Online (Sandbox Code Playgroud)

问题是它只适用于非成员函数,例如:


function foo(x, y)
{
    alert(x + y);
}

var bar = foo.curry(1);
bar(2); // alerts "3"
Run Code Online (Sandbox Code Playgroud)

如何将咖喱函数重新应用于成员函数,如:

function Foo()
{
    this.z = 0;

    this.out = function(x, y)
    {
        alert(x + y + this.z);
    }
}

var bar = new Foo;
bar.z = 3;
var foobar = bar.out.curry(1);
foobar(2); // should alert 6;
Run Code Online (Sandbox Code Playgroud)

Pru*_*sse 4

而不是你的curry函数,只需使用bind类似的:

function Foo()
{
    this.z = 0;

    this.out = function(x, y)
    {
        alert(x + y + this.z);
    }
}

var bar = new Foo;
bar.z = 3;
//var foobar = bar.out.curry(1);
var foobar = bar.out.bind(bar, 1);
foobar(2); // should alert 6;
Run Code Online (Sandbox Code Playgroud)