JavaScript Bang "!"函数与前导分号 ";"IIFE

标签 javascript function concatenation iife

Airbnd suggests我这样做:

!function() {
  // ...
}();

因为:

This ensures that if a malformed module forgets to include a final semicolon there aren't errors in production when the scripts get concatenated.

bang 让我可以绕过语言的语法规则:

// Evaluated in Chromium 34 console.
function(){}(); // => SyntaxError: Unexpected token (
!function(){}(); // => true

当连接其他模块时,bang 似乎可以解决问题:

!function(){}();function(){}(); // => SyntaxError: Unexpected token (
!function(){}();!function(){}(); // => true
(function(){}());!function(){}(); // => true

但是它似乎实际上并不“安全”,因为如果其他人在他的脚本末尾没有分号:

!function(){}()!function(){}(); // => SyntaxError: Unexpected token !
(function(){}())!function(){}(); // => SyntaxError: Unexpected token !

似乎前导分号 IIFE 更好。

;(function() {
  // ...
}());

!function(){}();(function(){}()); // => undefined
(function(){}());(function(){}()); // => undefined
!function(){}();;(function(){}()); // => undefined
(function(){}());;(function(){}()); // => undefined

我错过了什么吗?使用爆炸“!”真的可以接受吗?函数或前导分号“;” IIFE 真正优越是因为它们连接的方式吗?

最佳答案

那里总是有 IEFE。无论您将它们括在括号中还是在它们前面加上 ! 都是您的选择,并且没有什么区别。您需要其中任何一个来强制将函数解析为表达式。参见 javascript function leading bang ! syntax了解详情。

是否为整个结构加上前缀 ; 以防止错误与编写不佳的脚本 (What does the leading semicolon in JavaScript libraries do?) 连接是完全无关。您可以根据需要混合模式:

 !function(){…}() // not safe for arbitrary concatenation
 (function(){…}()) // not safe for arbitrary concatenation either
;!function(){…}()
;(function(){…}())

但是,有一种连接情况,其中 ()! 确实有所不同:如果连接两个脚本,中间有一个换行符,并且前者不以分号结尾。这确实允许 automatic semicolon insertion to jump in - 当下一行确实以一声巨响开始时!

1 + 2             // script A
!function(){…}(); // script B
// works!

1 + 2              // script A
(function(){…}()); // script B
// runtime error: "2 is not a function" (or whatever the previous line ends in)

我们了解到:始终以分号结束您的脚本。使用智能串联。如果您需要安全地防止哑连接,请以分号开始您的脚本。

关于JavaScript Bang "!"函数与前导分号 ";"IIFE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24067605/

相关文章:

javascript - 将表导出为 CSV - 将字符串格式问题导出到单独的单元格中

java - 泛型 Java 8 上的调用方法

arrays - 尝试查找任何 int 数组时出错

postgresql - 在 postgresql 中连接两个 int 值

javascript - 变量范围(module.exports + socket.io 设置)

javascript - React 如何连接 JS 文件和 HTML 文件

javascript - 拖放排序元素后创建重复项

c - 从输入动态分配矩阵 - C

javascript - 有没有减少分数的JavaScript函数

hash - 如何破解原像由多个单词组成的SHA-256?