这三种模块模式有什么区别?
1)function () {
// code here...
}();
2)(function () {
// code here...
})();
3)(function () {
// code here...
}());
有什么区别(特别是第三个变体)?它们都一样吗?
1)function () {
// code here...
}();
2)(function () {
// code here...
})();
3)(function () {
// code here...
}());
What are the differences (especially third variant)? Are they all the same?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第一个给出了语法错误。第二个和第三个版本定义了一个匿名函数并立即执行它。第二个和第三个版本也称为立即调用函数表达式。
您可能还会遇到类似这样的另一个版本。这在功能上与第二和第三版本相同,但它只是否定了返回值。
First one gives a syntax error. Second and third versions define a anonymous function and immediately execute it. Second and third versions are also called Immediately Invoked Function Expressions.
You might also encounter another version which looks like this. This is equal in functionality to 2nd and 3rd version but it just negates the return value.
2和3完全等价。它们之间没有功能差异。
1 是语法错误。由于函数没有用方括号括起来,因此它被视为函数声明。这是无效的,因为函数声明需要命名。括号使其成为“函数表达式”;这些不需要命名。
2 and 3 are exactly equivalent. There is no functional difference between them.
1 is a syntax error. Because the function is not wrapped in brackets, it is treated as a function declaration. It is invalid because function declaration need to be named. The brackets make it a "function expression"; these do not need to be named.
第一个无效,但是您可以执行以下操作来使其工作:
正如其他答案指出的那样,第二个和第三个之间没有区别,它们是相同的。
除了使用括号之外,以下也是有效的:
注意: 人们过去常常将这些函数称为“自执行匿名函数”,但该术语是不正确的。现在它们被称为“立即调用函数表达式 (IIFE)”,发音为“iffy”!
1st one is not valid, however you can do following instead to make it work:
As other answers pointed out that there is no difference between 2nd and third, they are same.
Instead of using parenthesis, following is also valid:
Note: People used to call these functions 'Self-Executing Anonymous Function' but the term is incorrect. Now they are called 'Immediately Invoked Function Expressions (IIFE)' pronounced "iffy"!