当前位置:网站首页>Deep Copy Event bus
Deep Copy Event bus
2022-07-02 12:27:00 【Il n'y a pas d'eau dans la mer】
Un.、Copie profonde
1、JSON.stringify

2、Version1 : Copie profonde personnalisée - Réalisation de base
// Déterminer si une valeur est un objet
function isObject(value) {
const valueType = typeof value;
return value !== null && (valueType === "object" || valueType === "function");
}
function deepClone(originValue) {
// Pour juger ce qui arriveoriginValueEst - ce un type d'objet
if (!isObject(originValue)) {
return originValue;
}
const newObject = {
};
for (const key in originValue) {
newObject[key] = deepClone(originValue[key]);
}
return newObject;
}
// Code d'essai
const obj = {
name: "chen",
age: 23,
friends: {
name: "zhangsan",
address: {
city: "Guangzhou",
},
},
};
const newObj = deepClone(obj);
console.log(newObj === obj);
obj.friends.name = "lisi";
console.log(newObj);
3、Version2 : Copie profonde personnalisée - Tableau、Fonctions、Symbol、Set、MapCopie
// Déterminer si une valeur est un objet
function isObject(value) {
const valueType = typeof value;
return value !== null && (valueType === "object" || valueType === "function");
}
function deepClone(originValue) {
// Déterminer si c'est unSetType
if (originValue instanceof Set) {
return new Set([...originValue]);
}
// Déterminer si c'est unMapType
if (originValue instanceof Map) {
return new Map([...originValue]);
}
// Jugement si ouiSymbolDevalue,Alors créez un nouveauSymbol
if (typeof originValue === "symbol") {
return Symbol(originValue.description);
}
// Fonction de jugement, Le multiplexage direct de la fonction , Pas besoin de copier ,this Est également lié dynamiquement
if (typeof originValue === "function") {
return originValue;
}
// Pour juger ce qui arriveoriginValueEst - ce un type d'objet
if (!isObject(originValue)) {
return originValue;
}
// Juge que l'objet entrant est un tableau, Ou un objet normal
const newObject = Array.isArray(originValue) ? [] : {
};
for (const key in originValue) {
newObject[key] = deepClone(originValue[key]);
}
// SymbolEn tant quekey,for C'est impossible à traverser
// C'est exact.SymbolDekeyTraitement spécial
const symbolKeys = Object.getOwnPropertySymbols(originValue);
for (const sKey of symbolKeys) {
newObject[sKey] = deepClone(originValue[sKey]);
}
return newObject;
}
let s1 = Symbol("aaa");
let s2 = Symbol("bbb");
// Code d'essai
const obj = {
name: "chen",
age: 23,
friends: {
name: "zhangsan",
address: {
city: "Guangzhou",
},
},
hobbies: ["a", "b", "c"],
foo: function () {
console.log("foo");
},
[s1]: "abc",
s2: s2,
set: new Set(["a", "b", "c"]),
map: new Map([
["aaa", "bbb"],
["bbb", "ccc"],
]),
};
const newObj = deepClone(obj);
console.log(newObj === obj);
obj.friends.name = "lisi";
console.log(newObj);
3、Version3 : Copie profonde personnalisée - Traitement des références circulaires
// Déterminer si une valeur est un objet
function isObject(value) {
const valueType = typeof value;
return value !== null && (valueType === "object" || valueType === "function");
}
function deepClone(originValue, map = new WeakMap()) {
// Déterminer si c'est unSetType
if (originValue instanceof Set) {
return new Set([...originValue]);
}
// Déterminer si c'est unMapType
if (originValue instanceof Map) {
return new Map([...originValue]);
}
// Jugement si ouiSymbolDevalue,Alors créez un nouveauSymbol
if (typeof originValue === "symbol") {
return Symbol(originValue.description);
}
// Fonction de jugement, Le multiplexage direct de la fonction , Pas besoin de copier ,this Est également lié dynamiquement
if (typeof originValue === "function") {
return originValue;
}
// Pour juger ce qui arriveoriginValueEst - ce un type d'objet
if (!isObject(originValue)) {
return originValue;
}
if(map.has(originValue)) {
return map.get(originValue)
}
// Juge que l'objet entrant est un tableau, Ou un objet normal
const newObject = Array.isArray(originValue) ? [] : {
};
map.set(originValue, newObject);
for (const key in originValue) {
newObject[key] = deepClone(originValue[key], map);
}
// SymbolEn tant quekey,for C'est impossible à traverser
// C'est exact.SymbolDekeyTraitement spécial
const symbolKeys = Object.getOwnPropertySymbols(originValue);
for (const sKey of symbolKeys) {
newObject[sKey] = deepClone(originValue[sKey], map);
}
return newObject;
}
let s1 = Symbol("aaa");
let s2 = Symbol("bbb");
// Code d'essai
const obj = {
name: "chen",
age: 23,
friends: {
name: "zhangsan",
address: {
city: "Guangzhou",
},
},
hobbies: ["a", "b", "c"],
foo: function () {
console.log("foo");
},
[s1]: "abc",
s2: s2,
set: new Set(["a", "b", "c"]),
map: new Map([
["aaa", "bbb"],
["bbb", "ccc"],
]),
};
// Il y a un problème de référence circulaire
obj.info = obj;
const newObj = deepClone(obj);
console.log(newObj === obj);
obj.friends.name = "lisi";
console.log(newObj);
2.、Bus d'événements

class MYEventBus {
constructor() {
this.eventBus = {
};
}
on(eventName, eventCallback, thisArg) {
let handlers = this.eventBus[eventName];
if (!handlers) {
handlers = [];
this.eventBus[eventName] = handlers;
}
handlers.push({
eventCallback, thisArg });
}
off(eventName, eventCallback) {
let handlers = this.eventBus[eventName];
if (!handlers) {
return;
}
const newHandlers = [...handlers];
for (let i = 0; i < newHandlers.length; i++) {
const handler = newHandlers[i];
if (handler.eventCallback === eventCallback) {
const index = handlers.indexOf(handler);
handlers.splice(index, 1);
}
}
}
emit(eventName, ...payload) {
const handlers = this.eventBus[eventName];
if (!handlers) {
return;
}
handlers.forEach((handler) => {
handler.eventCallback.apply(handler.thisArg, payload);
});
}
}
const eventBus = new MYEventBus();
// main.js, Écouter, Paramètres:Nom de l'événement, Avec les paramètres passés payload
eventBus.on(
"abc",
function (payload) {
console.log("Écouterabc", this);
},
{
name: "zhangsan" }
);
// Est capable d'écouter plusieurs événements
const handleCallback = function (payload) {
console.log("Écouterabc", this);
};
eventBus.on("abc", handleCallback, {
name: "zhangsan" });
// utils.js
eventBus.emit("abc", 123);
// Supprimer
eventBus.off("abc", handleCallback);
eventBus.emit("abc", 123);
边栏推荐
猜你喜欢

Sort---

Map and set

Initial JDBC programming

Sweetheart leader: Wang Xinling

使用Sqoop把ADS层数据导出到MySQL

Mysql database foundation

Docker compose configuration mysql, redis, mongodb

Programmers can't find jobs after the age of 35? After reading this article, you may be able to find the answer

drools决策表的简单使用

倍增 LCA(最近公共祖先)
随机推荐
Jenkins用户权限管理
From scratch, develop a web office suite (3): mouse events
字符串回文hash 模板题 O(1)判字符串是否回文
Mysql database foundation
AAAI 2022 | Peking University & Ali Dharma Institute: pruning and compression of pre training language model based on comparative learning
Lombok common annotations
JZ63 股票的最大利润
drools执行完某个规则后终止别的规则执行
Go学习笔记—多线程
String palindrome hash template question o (1) judge whether the string is palindrome
post请求体内容无法重复获取
jenkins 凭证管理
Post request body content cannot be retrieved repeatedly
Leetcode122 the best time to buy and sell stocks II
(C语言)3个小代码:1+2+3+···+100=?和判断一个年份是闰年还是平年?和计算圆的周长和面积?
倍增 LCA(最近公共祖先)
Full link voltage measurement
子线程获取Request
LeetCode—<动态规划专项>剑指 Offer 19、49、60
堆(優先級隊列)