front-end-interview-handbook/packages/quiz/questions/explain-why-the-following-d.../zh-CN.mdx

18 lines
1.2 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: '解释这为什么不能以IIFE工作: `function foo(){ }();`. 为了使它成为一个IIFE需要作出哪些改变'
---
IIFE 是 Immediately Invoked Function Expressions 的缩写,即立即调用函数表达式。 JavaScript 解析器读取`function foo(){ }();` 作为 `function foo(){ }` 和 `(); `, 如果前者是一个 _函数声明_, 而后者是一对括号, 则试图调用函数, 但没有指定名称, 因此,它抛出`Uncaught SyntaxError: Unexpected token )`。
这里有两种方法修复它,涉及添加更多括号:`(function foo(){ })()` 和 `(function foo(){ }())` 以 `function` 开头的语句被认为是*函数声明*;通过将这个函数包裹在"() "中,它成为一个*函数表达式*,然后可以用后面的`()`执行。 这些函数不会在全局范围内暴露,如果你不需要在代码里提及,你甚至可以省略它的名称。
您也可以使用 `void` 操作符:`void function foo(){ }();`. 不幸的是,这种做法有一个问题。 对给定表达式的执行结果总是\`undefined',所以如果你的 IIFE 函数返回任何东西,你就不能使用它。 举个例子:
```js
const foo = void (function bar() {
return 'foo';
})();
console.log(foo); // undefined
```