【发布时间】:2010-11-28 15:47:09
【问题描述】:
我刚刚在Immediately-Invoked Function Expressions 上阅读了Ben Alman 的文章并想知道这部分,他在其中介绍了函数表达式和闭包(还没有真正与IIFE 相关):
// ...doesn't it stand to reason that the function expression itself can // be invoked, just by putting () after it? function(){ /* code goes here */ }(); // This works! Well, almost. A minor JavaScript syntax issue actually // requires that ambiguity between function declarations and function // expressions be eliminated, which can be done by wrapping the function // expression in parens. // The following pattern is used universally to create an anonymous // closure with "privacy": (function(){ /* code goes here */ })(); // This parens syntax is also valid (I prefer the previous version): (function(){ /* code goes here */ }());
最后一部分让我印象深刻。谁能解释一下为什么调用函数表达式有两种不同的语法版本?
是否有意引入这种语法只是为了调用匿名闭包?还是它是其他语法属性的副产品?
为什么第二个版本仍然有效?从解析器的角度来看,第一个对我来说很有意义。第一对括号计算为一个函数对象,第二对调用这个函数对象。但是第二个呢?看起来它并没有解决上面提到的语法歧义。
谁能告诉我这里缺少什么?
【问题讨论】:
标签: javascript syntax closures