当前位置:网站首页>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);
边栏推荐
- Sub thread get request
- Map and set
- Test shift left and right
- AI mid stage technology research
- 寻找二叉树中任意两个数的公共祖先
- Lekao: 22 year first-class fire engineer "technical practice" knowledge points
- drools执行完某个规则后终止别的规则执行
- Embedded Software Engineer career planning
- Take you ten days to easily finish the finale of go micro services (distributed transactions)
- Writing method of then part in drools
猜你喜欢

初始JDBC 编程

堆(優先級隊列)

Discrimination of the interval of dichotomy question brushing record (Luogu question sheet)
![[FFH] little bear driver calling process (take calling LED light driver as an example)](/img/e7/153ae9f1befc12825d277620049f9d.jpg)
[FFH] little bear driver calling process (take calling LED light driver as an example)

CONDA common command summary

Sweetheart leader: Wang Xinling

Docker compose configuration mysql, redis, mongodb

Differences between nodes and sharding in ES cluster

高性能纠删码编码

Is the neural network (pinn) with embedded physical knowledge a pit?
随机推荐
CV2 in OpenCV VideoWriter_ Fourcc() function and cv2 Combined use of videowriter() function
Leetcode - Sword finger offer 51 Reverse pairs in an array
Leetcode739 daily temperature
记录一下MySql update会锁定哪些范围的数据
Tas (file d'attente prioritaire)
drools动态增加、修改、删除规则
OpenCV中cv2.VideoWriter_fourcc()函数和cv2.VideoWriter()函数的结合使用
Record the range of data that MySQL update will lock
Lekao: 22 year first-class fire engineer "technical practice" knowledge points
Leetcode209 subarray with the smallest length
Drools dynamically add, modify, and delete rules
堆(优先级队列)
SparkContext: Error initializing SparkContext解决方法
Fresh, 2022 advanced Android interview must know 100 questions (interview questions + answer analysis)
Distributed machine learning framework and high-dimensional real-time recommendation system
Full link voltage measurement
JZ63 股票的最大利润
Leetcode922 按奇偶排序数组 II
Sort---
初始JDBC 编程