admin管理员组文章数量:1332873
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
noradd5
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
1 Answer
Reset to default 8Probably 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}
本文标签: javascriptHow to do currying with UnderscoreJSStack Overflow
版权声明:本文标题:javascript - How to do currying with UnderscoreJS? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742307993a2450301.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论