How to partially apply member functions in JavaScript?

I currently have a partial application function that 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 example:

 function foo(x, y) { alert(x + y); } var bar = foo.curry(1); bar(2); // alerts "3" 

How can I rephrase a curry function that will 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; 
+6
source share
2 answers

Instead of your curry function, just use 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; 
+4
source

You're close this.z inside this.out refers to this on the scope of the function itself, and not on the Foo () function. If you want it to refer to this, you need to save the 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/

+2
source

Source: https://habr.com/ru/post/892255/


All Articles