怎么可能将参数传递给另一个同名函数中的内部函数?

How could it be possible to pass arguments to inner function inside another one with same name?

我是 JavaScript 的新手,是从 Freecodecamp 学习的。这是学习高阶箭头函数时的脚本之一。 我完全看不懂,下面的例子中有两个同名的函数吗?参数在哪里传递? inside 内部函数还是外部函数? 如果答案是外部函数,那怎么可能,因为外部函数似乎没有任何参数。

const increment = (function(){
    return function increment(number, value){
        return number + value;
    };
})();
console.log(increment(5,2));

分配给 increment 常量的函数包装了一个 IIFE(立即调用的函数表达式)。这意味着这个函数,顾名思义,会立即被调用并执行。然后它 returns 对在 IIFE 中声明的函数的引用。

const increment = (function(){
  return function increment(number, value){
    return number + value;
  };
})();

结果与此相同:

const increment = function increment(number, value){
  return number + value;
};

这是一个命名函数表达式。如果您遵循此模式,则允许变量和函数具有相同的名称。尝试在控制台中定义它,就像在第二个代码块中一样。

这里的区别在于变量 increment 只是对函数 increment.

的引用

但在您的例子中,function increment 是在匿名函数的范围内 定义的。 increment 函数名称仅在该匿名函数的范围内可用。然后返回对 increment 函数的引用。

虽然可以省略 IIFE,因为它没有做任何不同的事情。如果你想合并一个闭包来隐藏一些变量,它可以增加一些价值,例如:

const increment = (function(){
  const hiddenValue = 2;
  return function increment(number, value){
    return number + value + hiddenValue;
  };
})();

现在每次调用 increment 时,hiddenValue 都会添加到公式中。这样你就可以创建一种全局变量,它存在于 IIFE 的范围内,不会污染你的实际全局范围。

return function increment(number, value){
    return number + value;
};

在上面的代码中,函数名并不重要,删除它也不会改变任何事情。 唯一对外界重要的函数名是常量名。 这里作为伪代码:

const increment = (anonymous func (return a func)) (self call);

如果没有 LHS(左侧)分配,执行后所有内容都会丢失。

你可以把两个函数放在一起,然后在主函数里面调用函数 但在另一个之外

function firstOne(){
  console.log('first function is working.')
  function secondOne(){
    console.log('second function is working')
  }secondOne();
}firstOne()