我知道WeakMap和WeakSet由于安全原因不能迭代,即“”,但这意味着不能像克隆Map或Set ( cloned_map = new Map(existing_map), cloned_set = new Set(existing_set) )那样克隆WeakMap或WeakSet。
如何在Javascript中克隆WeakMap或WeakSet?所谓克隆,我指的是创建具有相同弱引用的另一个WeakMap或WeakSet。
发布于 2022-11-30 18:47:10
这是可以做到的,相信您在运行代码之前,就可以通过跟踪WeakMap.prototype.set和WeakMap.prototype.delete来生成一个弱映射。
然而,创建一个克隆需要我保持我自己对事物的看法,这样可能不会导致垃圾收集弱映射;-;
//the code you run first
(()=>{
let MAPS=new Map()
let DELETE=WeakMap.prototype.delete, SET=WeakMap.prototype.set
let BIND=Function.prototype.call.bind(Function.prototype.bind)
let APPLY=(FN,THIS,ARGS)=>BIND(Function.prototype.apply,FN)(THIS,ARGS)
WeakMap.prototype.set=
function(){
let theMap=MAPS.get(this)
if(!theMap){
theMap=new Map()
MAPS.set(this,theMap)
}
APPLY(theMap.set,theMap,arguments)
return APPLY(SET,this,arguments)
}
WeakMap.prototype.delete=
function(){
let theMap=MAPS.get(this)
if(!theMap){
theMap=new Map()
MAPS.set(this,theMap)
}
APPLY(theMap.delete,theMap,arguments)
return APPLY(DELETE,this,arguments)
}
function cloneWM(target){
let theClone=new WeakMap()
MAPS.get(target).forEach((value,key)=>{
APPLY(SET,theClone,[key,value])
})
return theClone
}
window.cloneWM=cloneWM
})()
//the example(go on devtools console to see it properly)
let w=new WeakMap()
w.set({a:1},'f')
w.set({b:2},'g')
w.set(window,'a')
w.delete(window)
console.log([w,cloneWM(w)])
console.log("go on devtools console to see it properly")
https://stackoverflow.com/questions/74610392
复制相似问题