IIFE(立即执行函数表达式)

来源:互联网 发布:淘宝运营工资怎么样 编辑:程序博客网 时间:2024/06/02 01:16

立即执行函数表达式

形式:

var a=2;(function foo() {    var a=3;    console.log(a);})();

或者:

var a=2;(function foo() {    var a=3;    console.log(a);}());

上述两种形式都是合法的,全凭个人喜好使用。
IIFE中的函数名不是必须的,可以使用匿名函数。

IIFE使用场景:

  • “隐藏”内部变量和函数定义,防止外部作用域访问,防止变量和函数污染,例如:
var a=2;function foo() {    var a=3;    console.log(a);}foo();//3console.log(a);//2

虽然上述代码是合法的,但是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);});