自动执行匿名 JavaScript 函数的括号位置? [英] Location of parenthesis for auto-executing anonymous JavaScript functions?
问题描述
我最近比较了 json2.js 与我在项目中使用的版本相比,我注意到函数表达式的创建和自执行方式有所不同.
I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.
用于将匿名函数包裹在括号中然后执行的代码,
The code used to wrap an anonymous function in parenthesis and then execute it,
(function () {
// code here
})();
但现在它将自动执行的函数包装在括号中.
but now it wraps the auto-executed function in parenthesis.
(function () {
// code here
}());
在解释JavaScript的封装匿名函数语法的接受答案中,CMS有一条评论 表明(function(){})();
和 (function(){}());
都是有效的."
There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that "both: (function(){})();
and (function(){}());
are valid."
我想知道有什么区别?前者是否通过留下全局匿名函数来占用内存?括号应该放在哪里?
I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?
推荐答案
它们几乎相同.
第一个函数用括号括起来,使其成为一个有效的表达式并调用它.表达式的结果未定义.
The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.
第二个执行函数,自动调用周围的括号使其成为有效的表达式.它也评估为未定义.
The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.
我不认为有一种正确"的方法可以做到,因为表达式的结果是相同的.
I don't think there's a "right" way of doing it, since the result of the expression is the same.
> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
"foo"
> (function(){ return 'foo'}())
"foo"
这篇关于自动执行匿名 JavaScript 函数的括号位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!