js 函数之间使用参数的区别

Difference between js functions by using parameters

本文关键字:参数 区别 函数 之间 js      更新时间:2023-09-26

两者之间有什么区别:

// Example 1 sum(8,2)
console.log(sum(8,2));   // Outputs what??
// Example 2 sum(8)(2)
console.log(sum(8)(2));  // Outputs what??
function sum(x,y) {
return x+y;
}
function sum(x) { 
  return function(y){
     return x+y;
     }
}
为什么

使用一个而不是另一个,为什么?

你尝试做的事情叫做函数柯里

试试这个:

function sum(x) { 
   return function(y) { return x + y; } 
}; 
var sumWith4 = sum(4); 
var finalVal = sumWith4(5);
finalVal = sumWith4(8);

优点之一是它有助于重用抽象函数。例如,在上面的例子中,我可以重用 sumWith4 将 4 添加到任何数字中,而无需显式调用 sum(4,5)。这是一个非常简单的例子。在某些情况下,函数的一部分将根据第一个参数进行评估,另一部分将根据第二个参数进行评估。因此,您可以通过为第一个参数提供分部函数来创建分部函数,然后为多个不同的第二个参数重复重用分部函数。

我假设你的意思是问调用函数之间的区别,如下所示:

  1. someFunction(x, y)
  2. someFunction(x)(y)

这发生在使用闭包时,闭包恰好是一个概念,其中内部函数可以承载创建它的环境。

var sum = function (x){
  return function(y) {
     return x+y;
  };
};
var addWith5 = sum(5);
/* 
   This will return a function and not a value
   addWith5 = function(y){return 5+y;}; 
*/
console.log(addWith5(5)); // this will return 11
/*
   You can also use add function directly
*/
console.log(sum(5)(6)); // this will return 11
/* 
   The function returned by sum(5), gets called with the parameter (6)
*/
 //Try using this, to make it more clear
 function a(x){ 
   return x;
 }(5);
 // returns 5

编辑删除了"闭包是JS概念"。