Awesome Function: module pattern
在线演示
利用函数的闭包不仅可以非常轻松地实现模块模式,并且可以自己创建一个模块管理器,就这么简单!
实现最简单的模块
1 2 3 4 5 6 7 8 9 10
| function simpleModule () { let sayHello = function sayHello (name) { return `Hi, ${name}` } return { sayHello: sayHello } } var module1 = simpleModule()
|
实现单例模式的模块
1 2 3 4 5 6 7 8 9 10
| var module2 = (function singleModule () { let hello = 'Hi, Module 2' let sayHello = function sayHello () { return hello } return { sayHello: sayHello } })()
|
实现保存对模块的内部引用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| var module3 = (function storeModule () { let store = {} let hello = 'Hi, Module 3' let sayHello = function sayHello () { return store.getHello() } let getHello = function getHello () { return hello } store = { sayHello: sayHello, getHello: getHello } return store })()
|
实现一个模块管理器
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
| var ModuleManager = (function moduleManager () { let modules = {} let register = function register (name, deps, impl) { for (let i = 0; i < deps.length; i++) { deps[i] = modules[deps[i]] } modules[name] = impl.apply(impl, deps) } let get = function get (name) { return modules[name] } return { register: register, get: get } })()
// 注册不带依赖的模块 ModuleManager.register('module4', [], function () { function sayHello (name) { return `Hello, ${name || 'module4'}` } return { sayHello: sayHello } })
ModuleManager.register('module5', ['module4'], function (module4) { function sayHello (name) { return `${module4.sayHello()}, this is Module 5` } return { sayHello: sayHello } })
module4 = ModuleManager.get('module4') module5 = ModuleManager.get('module5')
|