美文网首页
简单的依赖加载器实现

简单的依赖加载器实现

作者: 卡卡卡卡颂 | 来源:发表于2017-04-02 21:04 被阅读0次

为了验证闭包的学习,有必要实现一个简单的依赖加载器。

代码实现

var myModules=(function () {
    
    //保存所有定义的模块
    var modules={};

    /**
     *定义新模块,接收3个参数
     *name:模块名
     *deps:模块依赖的其他模块
     *impl:模块的定义
    **/ 
    function define(name,deps,impl) {
        
        //遍历依赖每一项,取出每个模块
        for (var i=0;i<deps.length;i++) {
            deps[i]=modules[deps[i]];
        }
        //将新模块存储进模块池,并注入依赖
        modules[name]=impl.apply(impl,deps);
    }
    //从模块池中取出模块
    function get (name) {
        return modules[name];
    }
    //暴露api
    return {
        define: define,
        get: get
    }
})()

使用

myModules.define('bar',[],function () {
    function hello (who) {
        //代码体
    }
    return {
        hello:hello
    }
})

myModules.define('foo',['bar'],function (bar) {
    functin hello2 () {
        //代码体
    }
    return {
        hello2:hello2
    }
})

var bar=myModules.get('bar');
var foo=myModules.get('foo');
  • 内容转自《你不知道的Javascript》

相关文章

网友评论

      本文标题:简单的依赖加载器实现

      本文链接:https://www.haomeiwen.com/subject/qszgottx.html