最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Is there any reason to wrap anonymous JavaScript functions in braces? - Stack Overflow

programmeradmin3浏览0评论
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.

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.

Share edited Mar 18, 2017 at 19:08 Jameson 6,6996 gold badges37 silver badges58 bronze badges asked Jan 26, 2010 at 6:32 RajatRajat 34.2k20 gold badges69 silver badges88 bronze badges 1
  • On large anonymous functions a convention is to wrap a function in brackets if your going to execute it. This allows peope to see whether your assigning the return of a self executing function or assigning the function to a variable. – Raynos Commented Oct 4, 2010 at 9:53
Add a ment  | 

3 Answers 3

Reset to default 11

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';
}();

The other form is still valid, though:

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

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

(The first form is not valid syntax to avoid ambiguities in the Javascript grammar.)

Yes, the first one sets the variable a as an anonymous variable, while the second one sets the variable a to the result of the function.

Edit: I read the first code wrong. The answer is no.

It is good practice (but not required) to wrap IIFEs (Immediately Invoked Function Expressions) in parenthesis for readability. If your function is long and the reader cannot see the end, the opening parenthesis calls the readers attention to the fact that there is something special about this function expression and forces them to look at the bottom to find out what it is.

发布评论

评论列表(0)

  1. 暂无评论