// 发布订阅,支持先订阅后发布和先发布后订阅
class EventEmitter {
status = {}; // 状态 map
value = {}; // 值map
eventMap = {}; // 事件map
on(task, fn) {
if (!this.eventMap[task]) {
this.eventMap[task] = [];
}
if(!this.status[task]) {
this.status[task] = "pending"
}
if (this.status[task] === "pending") {
this.eventMap[task].push(fn);
}
if (this.status[task] === "fulfilled") {
fn(this.value[task]);
}
}
emit(task, value) {
if (!this.eventMap[task]) {
this.eventMap[task] = [];
}
if(!this.status[task]) {
this.status[task] = "pending"
}
this.status[task] = "fulfilled";
if (!this.value[task]) {
this.value[task] = value;
}
while (this.eventMap[task].length > 0) {
let current = this.eventMap[task].shift();
current(value);
}
}
}
const event1 = new EventEmitter();
const task1 = (res) => { console.log("res 1 :>> ", res); };
const task2 = (res) => { console.log("res 2 :>> ", res); };
const task3 = (res) => { console.log("res 3 :>> ", res); };
// event1.emit("task", Math.random());
event1.on("task", task1);
event1.on("task", task2);
event1.on("task", task3);
event1.emit("task", Math.random());
// 深拷贝
function deepClone(obj, cache = new WeakMap()){
if(obj === null || typeof obj !== 'object') return obj;
if(obj instanceof Date) return new Date(obj)
if(obj instanceof RegExp) return new RegExp(obj)
if(cache.get(obj)) return cache.get(obj)
// 拿到实例对应的构造函数,new一个新的实例
let cloneObj = new obj.constructor()
cache.set(obj, cloneObj)
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
cloneObj[key] = deepClone(obj[key], cache) // 递归拷贝
}
}
return cloneObj
}
const obj = { name: 'Jack', address: { x: 100, y: 200 } }
obj.a = obj // 循环引用
const newObj = deepClone(obj)
console.log(newObj.address === obj.address)
发布订阅和深拷贝
最新推荐文章于 2022-07-09 09:00:00 发布