当前位置:网站首页>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);
边栏推荐
- ThreadLocal的简单理解
- 5g era, learning audio and video development, a super hot audio and video advanced development and learning classic
- High performance erasure code coding
- [C language] Yang Hui triangle, customize the number of lines of the triangle
- Less than three months after the programmer was hired, the boss wanted to launch the app within one month. If he was dissatisfied, he was dismissed immediately
- AAAI 2022 | Peking University & Ali Dharma Institute: pruning and compression of pre training language model based on comparative learning
- Map和Set
- Leetcode - Sword finger offer 51 Reverse pairs in an array
- CDA data analysis -- common knowledge points induction of Excel data processing
- Simple use of drools decision table
猜你喜欢

Jenkins用户权限管理

Brush questions --- binary tree --2

Take you ten days to easily finish the finale of go micro services (distributed transactions)

堆(優先級隊列)

Embedded Software Engineer career planning

【C语言】十进制数转换成二进制数

In development, why do you find someone who is paid more than you but doesn't write any code?

ES集群中节点与分片的区别

【工控老马】西门子PLC Siemens PLC TCP协议详解

SparkContext: Error initializing SparkContext解决方法
随机推荐
Jenkins voucher management
Drools terminates the execution of other rules after executing one rule
Use sqoop to export ads layer data to MySQL
ES集群中节点与分片的区别
LeetCode—剑指 Offer 59 - I、59 - II
Performance tuning project case
Lekao: 22 year first-class fire engineer "technical practice" knowledge points
Day12 control flow if switch while do While guessing numbers game
(C语言)输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
Thesis translation: 2022_ PACDNN: A phase-aware composite deep neural network for speech enhancement
The differences and relationships among port, targetport, nodeport and containerport in kubenetes
Go学习笔记—多线程
求16以内正整数的阶乘,也就是n的阶层(0=<n<=16)。输入1111退出。
On data preprocessing in sklearn
The most understandable f-string tutorial in history, collecting this one is enough
Experiment of connecting mobile phone hotspot based on Arduino and esp8266 (successful)
Sse/avx instruction set and API of SIMD
Simple understanding of ThreadLocal
Go learning notes - multithreading
drools中then部分的写法