匿名函数就是没有名字的函数,匿名函数的作用是避免全局变量的污染以及函数名的冲突。匿名函数通常与自执行函数结合使用,因为匿名函数没有函数名,所以无法通过函数名调用,需要通过自执行调用。
在了解匿名函数自执行之前,需要先简单了解一下函数声明和函数表达式的概念。
函数声明
函数声明最重要的一个特征就是函数声明提升,意思是执行代码之前先读取函数声明,并使其在执行任何代码前可用。这意味着可以把函数声明放在调用它的语句之后,同时函数声明必须要有标识符做为函数名称。
fn(1);
function fn(x) {
console.log(x);
}
函数表达式
函数表达式和函数声明的区别在于,函数表达式在使用前必须先赋值,因为函数表达式必须等到解析器执行到它的所在的代码行时,才会真正的被解析。
var fn = function(x) {
console.log(x);
}
fn(1);
自执行函数表达式
上述函数表达式中,创建的函数叫做匿名函数,因为function关键字后面没有标识符。所以自执行的匿名函数其实就是立即调用的函数表达式。
// 在js中,()里面不能包含语句(只能是表达式),所以解析器在解析到function关键字的时候,会把它们当作function表达式,而不是正常的函数声明
(function() {
console.log("1");
} ());
(function() {
console.log("1");
})();
// 匿名函数执行放在中括号内
[function() {
console.log("1");
} ()];
// 如果对于其返回值没有要求的话
~ function() {
console.log("1");
} ();
! function() {
console.log("1");
} ();
+ function() {
console.log("1");
} ();
- function() {
console.log("1");
} ();
delete function() {
console.log("1");
} ();
typeof function() {
console.log("1");
} ();
void function() {
console.log("1");
} ();
// 使用new关键字
new function() {
console.log("1");
} ();
new function() {
console.log("1");
};// 如果不需要传递参数,括弧()可以省略
// 赋值符号=同样可以
var fn = function (x) {
console.log(x);
return 10;
}(3);
// &&,异或,逗号等操作符可以在函数表达式和函数声明上消除歧义的,所以一旦解析器知道其中一个已经是表达式了,其它的也都默认为表达式了
1, function() {
console.log("1");
} ();
1 ^ function() {
console.log("1");
} ();
1 > function() {
console.log("1");
} ();
// &&、|| 需要注意短路原理
// false && (表达式1) 是不会触发表达式1
true && function() {
console.log("1");
} ();
// true || (表达式2) 不会触发表达式2
false || function() {
console.log("1");
} ();
在function前面加!、+、 -甚至是逗号等到都可以起到函数定义后立即执行的效果,而()、!、+、-、=等运算符,都将函数声明转换成函数表达式,消除了javascript引擎识别函数表达式和函数声明的歧义,告诉javascript引擎这是一个函数表达式,不是函数声明,可以在后面加括号,并立即执行函数的代码。