# IIFE(立即执行函数)的各种写法

在js中,下面这种函数定义及调用是最常用的。

function fn(){
    console.log('hello world');
}
fn(); // hello world

但如果我们需要实现定义完就执行的函数,那我们就会用到IIFE(立即执行函数)

讲道理,我们执行函数的时候都是在函数名后面加上 () 就执行了,那我们试下直接在函数后面加上 ()

function fn(){
    console.log('hello world');
}(); // Uncaught SyntaxError: Unexpected token )

啊哦,好像不行诶...

在这里,为啥加个 () 就会报错呢?

我们单独在浏览器上运行下 ()

() // Uncaught SyntaxError: Unexpected token )

同样会报这个错呢...

呃...

其实呢,在编译器读取到我们前面定义的 function 的时候,由于 function 前面没有内容,所以编译器自动认为我们这个是一个函数声明。在把整个function认为是函数声明之后,后面的 () 就会被另起一行来执行。如下:

function fn(){
    console.log('hello world');
}

(); // Uncaught SyntaxError: Unexpected token )

所以我们只要避免编译器把 function 当成函数声明就可以了。😄

# 1. 把它定义成一个函数表达式

var fn = function() {
    console.log('hello world');
}(); // hello world

# 2. 在 function 前面加点东西

!function() {console.log('hello world');}(); // hello world
~function() {console.log('hello world');}(); // hello world
1&function() {console.log('hello world');}(); // hello world
1>>function() {console.log('hello world');}(); // hello world
1<<function() {console.log('hello world');}(); // hello world
1*function() {console.log('hello world');}(); // hello world
1/function() {console.log('hello world');}(); // hello world
1|function() {console.log('hello world');}(); // hello world
-function() {console.log('hello world');}(); // hello world

这里只要是不在乎返回值,其实很多操作符都是可以使用的

# 3.最后我们写点看起来更正常的东西(推荐使用)

(function() {console.log('hello world');}()); // hello world
(function() {console.log('hello world');})(); // hello world

其实这里不管用哪种方法,最后实现的目的都是为了消除代码歧义,让编译器可以按照我们预期的想法执行。