当前位置:网站首页>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);
边栏推荐
- In development, why do you find someone who is paid more than you but doesn't write any code?
- Natural language processing series (I) -- RNN Foundation
- Day12 control flow if switch while do While guessing numbers game
- 分布式机器学习框架与高维实时推荐系统
- 上传文件时,服务器报错:IOFileUploadException: Processing of multipart/form-data request failed. 设备上没有空间
- CONDA common command summary
- mysql表的增删改查(进阶)
- MySQL and PostgreSQL methods to grab slow SQL
- Thesis translation: 2022_ PACDNN: A phase-aware composite deep neural network for speech enhancement
- The blink code based on Arduino and esp8266 runs successfully (including error analysis)
猜你喜欢

MySQL and PostgreSQL methods to grab slow SQL

记录一下MySql update会锁定哪些范围的数据

Map和Set

CDA数据分析——AARRR增长模型的介绍、使用

测试左移和右移

Find the common ancestor of any two numbers in a binary tree

BOM DOM

China traffic sign detection data set

(C language) input a line of characters and count the number of English letters, spaces, numbers and other characters.

甜心教主:王心凌
随机推荐
CV2 in OpenCV VideoWriter_ Fourcc() function and cv2 Combined use of videowriter() function
MySQL与PostgreSQL抓取慢sql的方法
Docker-compose配置Mysql,Redis,MongoDB
Leetcode739 每日温度
Leetcode122 买卖股票的最佳时机 II
Drools dynamically add, modify, and delete rules
测试左移和右移
Sparkcontext: error initializing sparkcontext solution
上传文件时,服务器报错:IOFileUploadException: Processing of multipart/form-data request failed. 设备上没有空间
FastDateFormat为什么线程安全
Fresh, 2022 advanced Android interview must know 100 questions (interview questions + answer analysis)
Intel internal instructions - AVX and avx2 learning notes
二分刷题记录(洛谷题单)区间的甄别
Leetcode209 subarray with the smallest length
寻找二叉树中任意两个数的公共祖先
Go learning notes - multithreading
Codeforces 771 div2 B (no one FST, refers to himself)
Day12 control flow if switch while do While guessing numbers game
Lombok common annotations
Brush questions --- binary tree --2