# 解释封装的匿名函数语法

2020/09/29 21:21 · javascript ·  · 0评论

## 我知道的

``````function twoPlusTwo(){
}
twoPlusTwo();
``````

``````var twoPlusTwo = function(){
};
twoPlusTwo();
``````

``````(function(){
})();
``````

## 我不明白的

``````function(){
}();
``````

a的语法`FunctionDeclaration`如下：

``````function Identifier ( FormalParameterListopt ) { FunctionBody }
``````

`FunctionExpression`s：

``````function Identifieropt ( FormalParameterListopt ) { FunctionBody }
``````

``````(function () {
}());
``````

``````(function foo() {
}());
``````

``````function foo () {} // FunctionDeclaration

0,function foo () {} // FunctionExpression
``````

``````if (true) {
function foo() {
}
} else {
function foo() {
}
}

foo(); // true? false? why?``````

Mozilla实现-Rhino，SpiderMonkey-具有不同的行为。它们的语法包含一个非标准的 Function语句，这意味着该函数将在运行时而不是在解析时进行评估，因为它会与`FunctionDeclaration`s一起发生在这些实现中，我们将定义第一个函数。

1-一个函数，该函数通过将Function构造函数分配给变量乘法

``````var multiply = new Function("x", "y", "return x * y;");
``````

2-名为乘法的函数的函数声明

``````function multiply(x, y) {
return x * y;
}
``````

3-分配给变量乘法的函数表达式

``````var multiply = function (x, y) {
return x * y;
};
``````

4-命名函数表达式func_name，分配给变量multipli

``````var multiply = function func_name(x, y) {
return x * y;
};
``````

``````function someName() {
}();
``````

``````function someName() {
}

();
``````

``````var a = function b() {
// do something
};
a(); // works
b(); // doesn't work

var c = function d() {
window.setTimeout(d, 1000); // works
};
``````

14.1.20-运行时语义：评估

FunctionDeclaration`function` BindingIdentifier `(` FormalParameters `)` `{` FunctionBody `}`

1. 返回NormalCompletion（空）。

``````var r = eval("function f(){}");
console.log(r); // undefined``````

``````var r = eval("(function f(){})");
console.log(r); // function f(){}``````

1. 用（）括起来

2. 在其前面放置一个空运算符

3. 将其分配给变量。

`````` function (arg1) { console.log(arg1) }();
``````

``````(function(arg1, arg2){
//some code
})(var1, var2);
``````

``````(function(arg1, arg2){
//some code
}(var1, var2));
``````

``````void function(arg1, arg2){
//some code
}(var1, var2);
``````

``````  var ll = function (arg1, arg2) {
console.log(arg1, arg2);
}(var1, var2);
``````

``````var x = function(){
}();
``````

``````var module = (function(){
})();
``````

``````(function(){
})();
``````

``````function(){
}();
``````

``````function() { alert( 2 + 2 ); }
``````

``````(function() { alert( 2 + 2 ); })();
``````

``````! function() { console.log('yeah') }()
``````

``````!! function() { console.log('yeah') }()
``````

`!`-negation op将fn定义转换为fn表达式，因此，您可以立即使用调用它`()`与使用`0,fn def`相同`void fn def`

``````var x = 3;
var y = 4;