带有不同调用的Javascript函数汇总

时间:2019-01-28 06:57:57

标签: javascript

我应该如何使该功能与不同的调用一起使用?

查看警报中的呼叫:

function summ(a){
	return function(b){
		return a+b
	}
}

alert(summ(5)(10)) //work
alert(summ(5,10)) // not work

1 个答案:

答案 0 :(得分:3)

function summ(a,b){
  if (typeof b !== "undefined") { // check if b is present.
  	return a+b;
  }
  else {  // b is not there, return another function that `capture` a 
  	return function(b){
    	return a+b;
    }
  }
}

alert(summ(5)(10)) // work
alert(summ(5,10))  // work

基本上,您要使用的功能summ必须处理两种不同的情况。

如果不存在b,则您的函数需要返回另一个嵌入的函数,其值为a

如果存在b,它将作为正常函数返回a+b