實現 如 goole closure 相似功能模塊加載函數

看過goole  closure 的同窗都知道  其中定義一個類名函數時候只要  inlude("")   想加載某個模塊只要require("")就能夠利用:html

下面給出一個例子:app

<!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
相關文章
相關標籤/搜索