当前位置:网站首页>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);
边栏推荐
- Test shift left and right
- Day12 control flow if switch while do While guessing numbers game
- 子线程获取Request
- mysql索引和事务
- The programmer and the female nurse went on a blind date and spent 360. He packed leftovers and was stunned when he received wechat at night
- MySQL与PostgreSQL抓取慢sql的方法
- FastDateFormat为什么线程安全
- Leetcode - Sword finger offer 51 Reverse pairs in an array
- 记录一下MySql update会锁定哪些范围的数据
- Use sqoop to export ads layer data to MySQL
猜你喜欢
Tas (file d'attente prioritaire)
CDH6之Sqoop添加数据库驱动
(C language) 3 small Codes: 1+2+3+ · · +100=? And judge whether a year is a leap year or a normal year? And calculate the circumference and area of the circle?
CDA data analysis -- Introduction and use of aarrr growth model
Heap (priority queue)
Sweetheart leader: Wang Xinling
初始JDBC 编程
(C语言)3个小代码:1+2+3+···+100=?和判断一个年份是闰年还是平年?和计算圆的周长和面积?
Multiply LCA (nearest common ancestor)
【C语言】十进制数转换成二进制数
随机推荐
post请求体内容无法重复获取
Calculate the maximum path sum of binary tree
Leetcode - Sword finger offer 37, 38
记录一下MySql update会锁定哪些范围的数据
(C language) input a line of characters and count the number of English letters, spaces, numbers and other characters.
The programmer and the female nurse went on a blind date and spent 360. He packed leftovers and was stunned when he received wechat at night
High performance erasure code coding
AI中台技术调研
Leetcode - Sword finger offer 51 Reverse pairs in an array
堆(優先級隊列)
Lekao: 22 year first-class fire engineer "technical practice" knowledge points
Take you ten days to easily finish the finale of go micro services (distributed transactions)
Codeforces 771 div2 B (no one FST, refers to himself)
Leetcode topic [array] -540- single element in an ordered array
计算二叉树的最大路径和
In development, why do you find someone who is paid more than you but doesn't write any code?
The most understandable f-string tutorial in history, collecting this one is enough
Differences between nodes and sharding in ES cluster
Thesis translation: 2022_ PACDNN: A phase-aware composite deep neural network for speech enhancement
Jenkins用户权限管理