用于自动执行匿名JavaScript函数的括号的位置? [英] Location of parenthesis for auto-executing anonymous JavaScript functions?

查看:110
本文介绍了用于自动执行匿名JavaScript函数的括号的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近比较当前版本的 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
}());

CMS在解释JavaScript的封装匿名函数语法两者:(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?

推荐答案

它们实际上是一样的。

They're virtually the same.

第一个包围函数的括号使其成为有效表达式并调用它。表达式的结果是未定义的。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆