Skip to content

Commit 751f816

Browse files
committed
2020.11.17
1 parent 9a997e7 commit 751f816

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// 《JaVaScript中的模块》http://www.yexiaochen.com/JaVaScript%E4%B8%AD%E7%9A%84%E6%A8%A1%E5%9D%97/
2+
3+
/*
4+
在《你不知道的 JavaScript》中,给出了模块模式因具备的两个必要条件:
5+
6+
1. 必须有外部的封闭函数,该函数必须至少被调用一次(每次调用都会创建一个新的模块实例)。
7+
2. 封闭函数必须返回至少一个内部函数,这样内部函数才能在私有作用域中形成闭包,并且可以访问或者修改私有的状态。
8+
9+
从中我们可以看到一个比较重要的一点,从函数调用所返回的只有数据属性而没有闭包函数的对象并不是真正的模块。
10+
*/
11+
12+
// 1. 简单模块
13+
const leoModule = ((name = 'module') => {
14+
let id = 1, moduleName = name;
15+
const getModuleId = () => console.log(`moduleId:${id}`);
16+
const getModuleName = () => console.log(`moduleName:${name}`);
17+
const setModuleName = name => moduleName = name;
18+
return {
19+
getModuleId, getModuleName, setModuleName
20+
}
21+
})();
22+
23+
// console.log(leoModule.getModuleId())
24+
25+
// 2. 模块机制
26+
const moduleManager = (() => {
27+
let modules = {};
28+
const imports = (name, deps, module) => {
29+
deps = deps.map(item => modules[item]);
30+
modules[name] = module(...deps);
31+
}
32+
const exports = name => name && modules[name];
33+
return {
34+
imports, exports
35+
}
36+
})()
37+
38+
moduleManager.imports('leo', [], () => {
39+
const getName = name => console.log("name:", name);
40+
return { getName }
41+
})
42+
43+
moduleManager.imports('robin', ['leo'], m => {
44+
let name = 'robin2';
45+
const getName = () => m.getName(name);
46+
return { getName };
47+
})
48+
49+
const robin = moduleManager.exports("robin");
50+
robin.getName();

0 commit comments

Comments
 (0)