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"

次のように、メンバー関数に適用されるカレー関数を言い換えるにはどうすればよいですか。

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.z内部は、Foo()関数ではなく、関数自体にスコープされたthis.out参照の内部です。thisそれを参照したい場合は、それをキャプチャするための変数を格納する必要があります。

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 に答える