【问题标题】:Javascript anonymous function - definition [duplicate]Javascript匿名函数-定义[重复]
【发布时间】: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');
}()); 

这两个函数在评估后都会被调用。但我无法理解其中的区别。

【问题讨论】:

标签: javascript anonymous-function


【解决方案1】:

不,没有区别:这两个选项在语法上不同,但在语义上是等效的。考虑一个命名函数:

(foo())

对比

(foo)()

也许更清楚它们是如何相同的。

【讨论】:

  • 可能存在差异:new (foo)() 不等于 new (foo())
  • 啊,因为news 的优先级第一个例子等于(new (foo))()?好点,但我认为不值得将其添加到我的答案中,因为这个问题看起来将被删除。
猜你喜欢
  • 2013-11-22
  • 1970-01-01
  • 2015-02-19
  • 2013-12-18
  • 2012-02-23
  • 1970-01-01
  • 2013-02-08
  • 2013-08-29
  • 2016-03-27
相关资源
最近更新 更多