Possible Duplicate:
Difference between (function(){})(); and function(){}();
Are “(function ( ) { } ) ( )” and “(function ( ) { } ( ) )” functionally equal in JavaScript?
我只是想知道这两个示例之间是否存在差异(关于功能):
第一
(function foo() {
console.log("bar")
})()
第二
(function foo() {
console.log("bar")
}())
两者似乎都工作正常......
谢谢!
没有区别。事实上,您需要使用 ()
只是因为简单...
function() { console.log('bar'); } ();
... 不会被 JS 解析器正确识别。正如ES5 standard中所说:
Also, an ExpressionStatement cannot start with the function keyword
because that might make it ambiguous with a FunctionDeclaration.
另一种((...)
)解决方案是用一些一元运算符扩充此语句。两者...
+function() { console.log('bar'); } ();
...和...
!function() { console.log('bar'); } ();
... 会起作用。