实现 如 goole closure 类似功能模块加载函数

看过goole  closure 的同学都知道  其中定义一个类名函数时候只要  inlude("")   想加载某个模块只要require("")就可以利用:

下面给出一个例子:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>分模块加载</title>
    <style>


    </style>
</head>
<body>
<script>
    //*********定义加载模块方法  start **************//
    (function (window, undefined) {
        if (window.define) {
            return
        }
        function isFunction(obj) {
            return Object.prototype.toString.call(obj) === "[object Function]"
        }

        var MM = {};
        var initModuleName = "initRun";

        function require(name) {
            if (!MM[name]) {
                throw new Error("Module " + name + " is not defined.")
            }
            var module = MM[name];
            if (module.inited === false) {
                runModule(name)
            }
            return module.ret
        }

        function runModule(name) {
            var exports = {};
            var module = MM[name];
            if (isFunction(MM[name].factory)) {
                var ret = MM[name].factory.apply(undefined, [require, exports, undefined]);
                module.ret = ret === undefined ? exports : ret
            } else {
                module.ret = MM[name].factory
            }
            module.inited = true
        }

        function define(name, deps, factory) {
            if (MM[name]) {
                throw new Error("Module " + name + " has been defined already.")
            }
            if (isFunction(deps)) {
                factory = deps
            }
            MM[name] = {factory:factory, inited:false};
            if (name === initModuleName) {
                runModule(name)
            }
        }

        window.define = define
    })(window);
    //*********定义加载模块方法 end **************//

    //下面给一个使用的例子
    (function(){
        define('View/test',function(require){
            var testObj = function(){};
            testObj.prototype = {
                test : function(){
                    alert("我是小测试");
                }
            };
            return testObj;
        });
        //上面定义了当模块为initRun时候启动模块
        define('initRun',function(require){
            var test = require('View/test') ;
            var testObj = new test;

            testObj.test();

        })

    })()

</script>
</body>
</html>
View Code

 

 

 

posted @ 2014-02-06 16:05  xiezhenzhong  阅读(240)  评论(0编辑  收藏  举报