1.JS的四种设计模式
1.工厂模式
function createPerson(name, age, sex) {
const obj = new Object()
obj.name = name;
obj.age = age;
obj.sex = sex;
obj.sayHi = function () {
console.log('this.name');
}
return obj;
}
2.单例模式
let OnlyPerson = function (name, age) {
this.name = name;
this.age = age;
}
OnlyPerson.prototype.sayHi = function () {
console.log(this.name);
}
let getInstance = (
function () {
let Instance = null
return function (name, age) {
if (!Instance) {
Instance = new OnlyPerson(name, age);
}
return Instance
}
})()
3.沙箱模式
let sandbox = (function () {
function sayName() { }
function sayAge() { }
return {
sayName: sayName,
sayAge: sayAge
}
})()
4.发布者订阅模式
let Public = {
listen: function (key, fn) {
if (!this.list[key]) {
this.list[key] = []
}
this.list[key].push(fn)
},
trigger: function (key, ...args) {
let lists = this.list[key]
for (let fn of lists) {
fn.apply(this, ...args)
}
},
list: []
}