是否有一种方法可以创建Javascript中任何其他弱引用的WeakMap,用于存储键值对,其中键是字符串/数字,值是对象。
引用必须像这样工作:
const wMap = new WeakRefMap();
const referencer = {child: new WeakRefMap()}
wMap.set('child', temp.child);
wMap.has('child'); // true
delete referencer.child
wMap.has('child'); //false 我创建了一种树结构,它可以跟踪当前作用域中仍然使用的引用。
我将进行大量的合并,递归地清理一个深嵌套的结构对于这个用例来说是非常低效的。
发布于 2022-09-07 01:18:36
您可以使用WeakRef和FinalizationRegistry来解决这个问题。
下面是用TypeScript编写的一个示例:
class InvertedWeakMap<K extends string | symbol, V extends object> {
_map = new Map<K, WeakRef<V>>()
_registry: FinalizationRegistry<K>
constructor() {
this._registry = new FinalizationRegistry<K>((key) => {
this._map.delete(key)
})
}
set(key: K, value: V) {
this._map.set(key, new WeakRef(value))
this._registry.register(value, key)
}
get(key: K): V | undefined {
const ref = this._map.get(key)
if (ref) {
return ref.deref()
}
}
has(key: K): boolean {
return this._map.has(key) && this.get(key) !== undefined
}
}
async function main() {
const map = new InvertedWeakMap()
let data = { hello: "world!" } as any
map.set("string!", data)
console.log('---before---')
console.log(map.get("string!"))
console.log(map.has("string!"))
data = null
await new Promise((resolve) => setTimeout(resolve, 0))
global.gc() // call gc manually
console.log('---after---')
console.log(map.get("string!"))
console.log(map.has("string!"))
}
main()它必须使用-曝光-gc选项在node.js环境中运行。
发布于 2017-07-19 19:18:47
无法捕获删除操作。您可以做的是将数据封装在另一个obj中。
function referenceTo(value){
this.value=value;
}因此,如果删除了这个引用,就不能再访问它了。
var somedata=new referenceTo(5)
var anotherref=somedata;
//do whatever
delete somedata.value;
//cannot be accessed anymore
anotherref.value;//undefinedhttps://stackoverflow.com/questions/45199043
复制相似问题