单例模式
思想:基于单独的实例来管理某一个模块中的内容,实现模块之间的独立划分。也可以实现模块之间方法的相互调用。
使用window暴露方法(非单例模式)
(function () {
const arr = ['clp', '佩奇', '乔治']
function f1() {
console.log(arr)
}
function f2() {}
function f3() {}
// 向全局window对象中添加f1属性
window.f1 = f1
})()
f1() // ['clp', '佩奇', '乔治']
单例模式思想的例子
// 使用闭包产生独立的作用域,通过return对象的方式向外暴露方法。
const moduleA = (function (){
const arr = ['clp', '佩奇', '乔治']
function f1() {
console.log(arr)
}
function f2() {}
function f3() {}
return {
f1
}
})()
const moduleB = (function (){
const arr = ['clpPlus', '佩奇Plus', '乔治Plus']
function f1() {}
function f2() {}
function f3() {}
function f4() {}
function f5() {}
moduleA.f1() // ['clp', '佩奇', '乔治']
})()
命令模式
命令模式的例子
// 向外暴露的init方法中,按指定顺序执行内部的函数。
const moduleA = (function () {
const arr = ['clp', '佩奇', '乔治']
function f1() {
console.log(arr)
}
function f2() { }
function f3() { }
function f4() { }
function f5() { }
return {
init(){
f1()
f2()
f3()
f4()
}
}
})()