形式:
var a=2; (function foo() { var a=3; console.log(a); })();或者:
var a=2; (function foo() { var a=3; console.log(a); }());上述两种形式都是合法的,全凭个人喜好使用。 IIFE中的函数名不是必须的,可以使用匿名函数。
虽然上述代码是合法的,但是foo这个名称本身也“污染了全局作用域”,使用IIFE可以解决这个问题:
var a=2; (function foo() { var a=3; console.log(a);//3 })(); console.log(a);//2 将其当做函数调用并传递参数,例如: var a=2; (function IIFE(global) { var a=3; console.log(a); console.log(global.a); })(window); console.log(a); 解决undefined标识符默认值被错误覆盖导致的异常(不常见)。将一个参数命名为undefined,但是在对应的位置不传入任何值,这样就可以保证在代码块中undefined标识符的值真的是undefined: undefined=true;//一般不要这样做 (function IIFE(undefined) { var a; if(a===undefined) { console.log('Undefined is safe here'); } })(); 倒置代码运行顺序,将需要运行的函数放在第二位,在IIFE执行之后当做参数传递进去。这种模式略显冗长,但是有些人认为它更易理解。 var a = 2; (function IIFE(def) { def(window); })(function def(global) { var a=3; console.log(a); console.log(global.a); });