简体   繁体   English

如何使函数与顺序调用和仅一个调用一起工作

[英]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) ,如果要currifycurrify ,只需用curry包装它,如果使用lodash ,则可以使用lodash var curried = _.curry(function)来咖喱一个函数var curried = _.curry(function) ,使您的函数干净

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使javascript函数仅运行一次 - How make javascript function work only one time 如何让我的 function 只为一个部分工作 - How to make my function work for only for one section 如何确保一个 function 调用的回调仅在第二个 function 调用回调后执行 - how to make sure callback of one function call, gets executed only after callback of the second function call AngularJs:我有一个选择下拉列表,它在更改时仅调用一次函数。 每当更改时如何使它调用函数? - AngularJs: I have the select droplist that calls a function only once when changed. How can I make it call the function whenever it is changed? 仅当javascript函数返回true时,如何使表单调用php? - how to make form calls php only if javascript function returns true? 如何使 JavaScript 函数仅在桌面上工作 - How to make a JavaScript Function to work on desktop only 使用onload加载多个图像以调用函数,并且仅最后加载的一个调用该函数 - Multiple images being loaded with onload to call function and only last one loaded calls the function 如何在jQuery中进行一次函数调用 - How to make one time call to function in jquery 如何使用带有队列的承诺对不同的函数调用进行排序 - how to sequence varying function calls with promises with a queue 如何让function只对一个按钮起作用? Bootstrap-5 滚动到模态底部 - How to make function work only for one button? Bootstrap-5 scroll to modals bottom
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM