2

Javascript 菜鸟在这里。在阅读模块模式时。我注意到这个匿名函数在函数范围内有括号。我以前没有用过这个。我想更好地理解它。

// first example
(function(){
    //this is IIFE I always use to avoid globle var. I think the simple form of this is F();
})();

// second example
(function () {
    //However, what is this concept? what's the formal name of this function? 
}());

这两者之间的主要区别是什么?我如何理解第二个例子?

4

1 回答 1

2

通常你不需要包装括号,如果你删除那些你会看到它是一样的:

function(){}()
function(){}()

上面,这已经是一个 IIFE。

但是如果该函数不用作表达式,例如在赋值中,那么 JavaScript 会认为它是一个函数声明。要消除代码歧义并强制使用表达式,您可以执行各种操作,例如添加括号:

// Same thing
(function(){}())
(function(){})()

或使用一元运算符:

!function(){}()
+function(){}()
void function(){}()
于 2015-01-30T21:30:31.273 回答