闭包实现一个AMD模块化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
var Module = (function () {
let modules = []

function define (mod, dependencies, func) {
let depens = {}
dependencies.forEach((depend, key) => {
depens[depend] = modules[depend]
})

modules[mod] = func.call(func, depens)
}

function require (mod) {
return modules[mod]
}

return {
define,
require
}
})()

// test
Module.define('foo', [], function () {
function sayHi () {
console.log('say hi')
}

return {
sayHi
}
})

Module.define('bar', ['foo'], function (depends) {
function sayHello () {
depends.foo.sayHi()
console.log('say hello')
}

return {
sayHello
}
})

const bar = Module.require('bar')
bar.sayHello()

有点事做,晚上再补充。