6

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

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);
}

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


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

var bar = foo.curry(1);
bar(2); // alerts "3"

如何改写 curry 函数以应用于成员函数,如:

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;
4

2 回答 2

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;
于 2011-07-07T17:36:25.063 回答
2

你很近。this.zthis.out引用this范围内是函数本身,而不是 Foo() 函数。如果您希望它引用它,您需要存储一个变量来捕获它。

var Foo = function() {
    this.z = 0;
    var self = this;

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

http://jsfiddle.net/hB8AK/

于 2011-07-07T17:35:21.333 回答