模块加载原理(第二种)

var kModule = (function(){
    var modules = {}
    ,config = {}
    ,define = function(deps,factory){
        typeof deps == 'function' && (
            factory = deps,
            deps = []
        )
        if(!Array.isArray(deps)){
            deps = [deps];
        }
        var exports = function(name,impl){
            if(!modules[name]){
                kModule[name] = modules[name] = impl;
            }
        }
        typeof factory == 'function' && factory.apply(factory,[exports])
    }
    
    ,require = function(deps,handle){
        typeof deps == 'function' && (
            handle = deps,
            deps = []
        )
        if(!Array.isArray(deps)){
            deps = [deps];
        }
        for(let i = 0; i < deps.length; i++){
            deps[i] = modules[deps[i]]
        }
        handle.apply(handle,deps);
    }
    
    return {
        define:define,
        require:require,
    };
    
})();


kModule.define(function(exports){
    var initTable = function(){
        return "初始化表格模块";
    }
    var tableImpl = {
        initTable:initTable
    }
    exports('table',tableImpl)
});

//第一种调用方式
kModule.require('table',function(){
    var table = kModule.table
    alert(table.initTable());
});
//第二种调用方式
kModule.require('table',function(table){
    alert(table.initTable());
});

 

posted @ 2019-11-18 11:57  littleboyck  阅读(...)  评论(... 编辑 收藏