开发者

How to partially apply member functions in JavaScript?

开发者 https://www.devze.com 2023-03-18 14:15 出处:网络
I currently 开发者_如何学JAVAhave a partial-application function which looks like this: Function.prototype.curry = function()

I currently 开发者_如何学JAVAhave a partial-application function which looks like this:

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

The problem is that it only works for non-member functions, for instance:


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

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

How can I rephrase the curry function to be applied to member functions, as in:

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;


Instead of your curry function just use the bind like:

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;


You're close. this.z inside of this.out references the this scoped to the function itself, not the Foo() function. If you want it to reference that, you need to store a variable to capture it.

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

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

http://jsfiddle.net/hB8AK/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号