是否有任何理由将匿名JavaScript函数包装在大括号中? [英] Is there any reason to wrap anonymous JavaScript functions in braces?

查看:134
本文介绍了是否有任何理由将匿名JavaScript函数包装在大括号中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var a = function () {
    return 'test';
}();

console.log(a);

第一种情况的答案:测试

Answer in First Case : test

var a = (function () {
    return 'test';
})();

console.log(a);

第二种情况的答案:测试

Answer in Second Case : test

我正在使用第一种方法来创建自动执行功能。但是,我也看到了第二种方法。这两种方法有什么不同吗?结果显然是一样的。

I am using the the first approach to create self-executing functions. However, I have seen the second approach as well. Is there any difference in the two approaches ? The result is obviously the same.

推荐答案

第一种语法只有在将函数执行结果赋给变量时才有效,如果您只想执行该函数,则此表单将出现语法错误:

The first syntax is only valid if you assign the result of the function execution to a variable, If you just want to execute the function, this form would be a syntax error:

function(){
   return 'test';
}();

另一种形式仍然有效:

(function(){
    return 'test';
 })();

因此,第二个版本更灵活,可以更一致地使用。

Therefore the second version is more flexible and can be used more consistently.

(第一种形式不是避免Javascript语法中的含糊不清。)

这篇关于是否有任何理由将匿名JavaScript函数包装在大括号中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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