為了驗(yàn)證閉包的學(xué)習(xí),有必要實(shí)現(xiàn)一個(gè)簡(jiǎn)單的依賴加載器鸳址。
代碼實(shí)現(xiàn)
var myModules=(function () {
//保存所有定義的模塊
var modules={};
/**
*定義新模塊,接收3個(gè)參數(shù)
*name:模塊名
*deps:模塊依賴的其他模塊
*impl:模塊的定義
**/
function define(name,deps,impl) {
//遍歷依賴每一項(xiàng)窟赏,取出每個(gè)模塊
for (var i=0;i<deps.length;i++) {
deps[i]=modules[deps[i]];
}
//將新模塊存儲(chǔ)進(jìn)模塊池功戚,并注入依賴
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');
- 內(nèi)容轉(zhuǎn)自《你不知道的Javascript》
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者