看过goole closure 的同学都知道 其中定义一个类名函数时候只要 inlude("") 想加载某个模块只要require("")就可以利用:
下面给出一个例子:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<id>skldfjskdljf</id>
<script>
(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);
解释下上面代码 利用闭包保存了 MM对象 这个对象保存了 通过 defined 进行命名的对象 换句话说mm相当于 命名空间。
下面试利用的例子:
define("tools", function (require, exports) {
var tools =
function(){};
tools.prototype = {
testFun :
function(){
alert(6656);
}
};
return tools;
});
define("initRun",function(require, exports){
var commTool =
require("tools");//通过require 加载需要模块
var tools = new commTool;
tools.testFun();
});
</script>
</body>
</html>