最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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}
发布评论

评论列表(0)

  1. 暂无评论