首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Javascript中克隆“WeakMap”或“WeakSet”?

如何在Javascript中克隆“WeakMap”或“WeakSet”?
EN

Stack Overflow用户
提问于 2022-11-29 07:22:08
回答 1查看 78关注 0票数 0

我知道WeakMapWeakSet由于安全原因不能迭代,即“”,但这意味着不能像克隆MapSet ( cloned_map = new Map(existing_map), cloned_set = new Set(existing_set) )那样克隆WeakMapWeakSet

如何在Javascript中克隆WeakMapWeakSet?所谓克隆,我指的是创建具有相同弱引用的另一个WeakMapWeakSet

EN

回答 1

Stack Overflow用户

发布于 2022-11-30 18:47:10

这是可以做到的,相信您在运行代码之前,就可以通过跟踪WeakMap.prototype.setWeakMap.prototype.delete来生成一个弱映射。

然而,创建一个克隆需要我保持我自己对事物的看法,这样可能不会导致垃圾收集弱映射;-;

代码语言:javascript
复制
//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")

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74610392

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档