【发布时间】:2012-05-02 18:46:37
【问题描述】:
可能重复:
Location of parenthesis for auto-executing anonymous JavaScript functions?
Is there a difference between (function() {…}()); and (function() {…})();?
Two ways of immediate call to anonymous function (function(d){ }() ); and (function(x){ } )();
给定的两种声明和调用匿名函数的方式有区别吗?
选项 1:
(function(){
console.log('Declare and call anonymous function');
})();
选项 2:
(function(){
console.log('Declare and call anonymous function');
}());
这两个函数在评估后都会被调用。但我无法理解其中的区别。
【问题讨论】:
-
选项 1 将保证函数在调用之前已定义且可用。也许这样做是为了兼容性(浏览器在函数定义复杂的情况下可能表现得非常不同)。
-
选项 3: !function(){ console.log('声明并调用匿名函数'); }()
-
在stackoverflow.com/a/3783287/5445 上查看我的回答,没有实用 的区别,只有语法 层面的区别。
标签: javascript anonymous-function