JavaScript IIFE 评估未定义

JavaScript IIFE Evaluation is undefined

你好,我是 JavaScript 的初学者,我正在尝试弄清楚 IIFE 是如何工作的,但我仍然遇到一些麻烦。在讲座中我偶然发现了这个示例代码,下面代码的评估给出了结果“undefined”,而用“add()”调用函数 returns 1 我真的不明白为什么,因为函数是一个 IIFE。

var add = (function() {
       var counter = 0;

       return function() {
            counter += 1;
            return counter 
       }
})();
//Output: undefined

对于 IIFE,您需要将匿名函数包装在“( )”中,然后使用“();”调用它 它不允许声明。尝试删除声明。

(function() {
   var counter = 0;

   return function() {
        counter += 1;
        return counter 
   }
})();

有关详细信息,请参阅此处。 https://www.tutorialsteacher.com/javascript/immediately-invoked-function-expression-iife

您的 IIFE 是一个 factory function. In this case it returns a function, so that works. You can assign the result to a variable and subsequently run the resulting function. The counter variable is 'closed over',它将通过返回的函数进行操作(并返回),但 'outside world'.

无法访问它

// assign the result to a variable
const add = (function() {
  let counter = 0;
  return function() {
    counter += 1;
    return counter;
  }
})();

// add is a function: execute it a few times
add();
add();
console.log(add()); // => 3

你的 IIFE 没有问题。您只会看到 var 语句的结果。示例:

var x = function() {};
//=> undefined
var x = 42;
//=> undefined
var x = true;
//=> undefined

赋值表达式的计算结果为右边的值:

y = 10;
//=> 10

但是 var 声明本身 returns 什么都没有:

var y = 10;
//=> undefined

规范的相关部分:

VariableDeclaration : BindingPattern Initializer

  1. Let rhs be the result of evaluating Initializer.
  2. Let rval be ? GetValue(rhs).
  3. Return the result of performing BindingInitialization for BindingPattern passing rval and undefined as arguments.

https://tc39.es/ecma262/#sec-variable-statement