Cam*_*tin 63 javascript comparison closures jslint anonymous-function
我知道这很愚蠢,但这有什么区别:
(function() {
var foo = 'bar';
})();
Run Code Online (Sandbox Code Playgroud)
还有这个?
(function() {
var foo = 'bar';
}());
Run Code Online (Sandbox Code Playgroud)
JSLint告诉我们Move the invocation into the parens that contain the function,但我认为没有必要.
编辑:答案太酷了.~function,JSHint的替代方案以及jQuery对(/***/)();Crockford的解释的偏好!我以为我会得到一个"他们是同一件事"的答案.
你们通过upvotes决定最好的一个,我勾选它.
Ada*_*kis 49
没有区别.两者都是使JavaScript解析器将您的函数视为表达式而不是声明的有效方法.
请注意,+并且!也可以使用,并且有时使用minifiers来保存大小的字符:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
Run Code Online (Sandbox Code Playgroud)
编辑
正如@copy指出的那样,为了完整性,~它-也会起作用.
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
Run Code Online (Sandbox Code Playgroud)