IIFE 立即执行函数表达式-模块化

1)立即执行

2)表达式

3)括号,分号结束 | 前缀运算符 | 表达式上下文

4)只需要执行一次,内部变量无需维护,可用于初始化

(function( ) {
})( );
或 (
function( ){ }( ));
或通过前缀运算符强制执行表达式,可以无分号
+function() { }( ) 或在表达式上下文,不需要前缀或括号,无需调用就执行了 var ourter = function outter (){ }( )

4)可传入参数

var obj = {} ;
(function(export){
   export.add = function () { } ;
   export release = function () { } ;
})(this.obj = { })   // this 指向window对象

5)应用

a、用于模块化

var weekDay = (function(){
    var week = ["星期一","星期二","星期三","星期四","星期五"];
    return function (num) {
        return week[num];
    }
})()
console.log(weekDay(1))
var weekDay = (function(){
    var week = ["星期一","星期二","星期三","星期四","星期五"];
    return {
     name:function (num) {
            return week[num];
      },
      index:function (name) {
          return week.indexOf(name);
      }
    }
})() 
console.log(weekDay.name(1))
console.log(weekDay.index("星期二"))    
//缺点:当接口多时,不利于看 
(function(exports){
    var week = ["星期一","星期二","星期三","星期四","星期五"];
    exports.name = function (num) {
        return week[num];
    }
    exports.index = function (name) {
        return week.indexOf(name);
    }
})(this.weekDay = {});
console.log(weekDay.name(1))
console.log(weekDay.index("星期二"))
//缺点:每个模块都要定义一个全局变量存储,存在多个模块刚好使用相同名字问题
posted @ 2019-12-18 15:44  雨夜稻草  阅读(298)  评论(0编辑  收藏  举报