[英]How to make function work with sequence calls and with only one call
I'm trying to make a function work with this two calls: 我正在尝试使函数与这两个调用一起工作:
func(1)(2); // 3
func(1, 2); // 3;
What i'm trying to do: 我正在尝试做的是:
function func(x, y) {
return (function(y) {
return x + y;
}(y));
}
But this won't work at all when i try to call in sequence. 但是,当我尝试依次调用时,这根本不起作用。 Is there other way to achieve that? 还有其他方法可以实现吗?
function add(x, y) {
if (y) return x + y;
return function(y) {
return x + y;
};
}
This would work, but i think it could be a better solution. 这会起作用,但是我认为这可能是一个更好的解决方案。
Thanks. 谢谢。
What you are looking for is called currying , here is how you could do it. 您正在寻找的被称为currying ,这是您可以做到的。
function add(a, b){ if(typeof b !== 'undefined'){ return a + b; }else{ return function(c){ return a + c; } } } console.log(add(2, 3)); console.log(add(2)(3));
Also check this answer How to Write a function where the output for both “sum(2,3)” and “sum(2)(3)” will be 5 还要检查此答案如何编写一个函数,其中“ sum(2,3)”和“ sum(2)(3)”的输出均为5
IMO没有这样做的充分理由,您有一个函数func(1, 2)
,如果要currify
该currify
,只需用curry
包装它,如果使用lodash
,则可以使用lodash
var curried = _.curry(function)
来咖喱一个函数var curried = _.curry(function)
,使您的函数干净
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.