javascript - How to do currying with UnderscoreJS? - Stack Overflow

I am a bit experimenting with _.bind(...). I see how to force a function context with bind, but don

I am a bit experimenting with _.bind(...). I see how to force a function context with bind, but don't yet see how to do currying.

What I try is this:

 add = function(number) { this.sum = this.sum + number; }
 add5 = _.bind(add, { sum: 0 }, 5)

However, calling add5(), or add5(5) seems not to have some effects.

Any clues how to do wrap the arguments such that the context is preserved from one call to another?

I am a bit experimenting with _.bind(...). I see how to force a function context with bind, but don't yet see how to do currying.

What I try is this:

 add = function(number) { this.sum = this.sum + number; }
 add5 = _.bind(add, { sum: 0 }, 5)

However, calling add5(), or add5(5) seems not to have some effects.

Any clues how to do wrap the arguments such that the context is preserved from one call to another?

Share Improve this question edited Jan 28, 2016 at 13:55 poseid asked May 13, 2013 at 11:48 poseidposeid 7,15610 gold badges51 silver badges79 bronze badges 5
  • 1 Underscore has a _.partial, which I think you can use to curry. – Waleed Khan Commented May 13, 2013 at 11:53
  • Neither add nor add5 have effects, so what did you expect to happen? – Waleed Khan Commented May 13, 2013 at 11:59
  • I was expecting to get some numbers: 0, 5, 10, 15, ... – poseid Commented May 13, 2013 at 12:00
  • Where would they be printed? You have no code to show numbers. – Waleed Khan Commented May 13, 2013 at 12:03
  • 1 see also github./documentcloud/underscore/pull/474 – poseid Commented May 13, 2013 at 13:13
Add a ment  | 

1 Answer 1

Reset to default 8

Probably you want to do partial application, not currying/schönfinkeling. Underscore has the _.partial function for this:

function add(a, b) { return a+b; }
var add5 = _.partial(add, 5);

You can as well use _.bind, and it has some effects. For example:

var add5 = _.bind(add, null /*context is irrelevant*/, 5);
add5(3); // returns 8

Yet, your function did not return anything, and the context which you did change was not accessible. However:

var ctx1 = {sum: 0};
function add(a) { this.sum += a; } // returns nothing!
var addto1 = _.bind(add, ctx1);
addto1(5); // undefined
ctx1; // {sum: 5}

var add5to1 = _.bind(add, ctx1, 5);
add5to1(); // undefined
ctx1; // {sum: 10}

var ctx2 = {sum: 5};
add3to2 = _.bind(add, ctx2, 3);
add3to2(); // undefined
ctx2; // {sum: 8}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742307994a4419324.html

相关推荐

  • javascript - How to do currying with UnderscoreJS? - Stack Overflow

    I am a bit experimenting with _.bind(...). I see how to force a function context with bind, but don

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信