[英]Javascript Flyweight with WeakMap or WeakSet
I want a Flyweight object so I created an Object and stored it's instances in a Map like this: 我想要一个Flyweight对象,所以我创建了一个Object并将其实例存储在Map中,如下所示:
const FlyweightNumber = (function(){
"use strict";
const instances = new Map();
class FlyweightNumber{
constructor(number){
Object.defineProperty(this, 'number', {
value: number
});
if(!instances.get(number)){
instances.set(number, this);
}
else {
return instances.get(number);
}
}
toString() {
return this.number;
}
valueOf(){
return this.number;
}
toJSON(){
return this.number;
}
}
return FlyweightNumber;
})();
module.exports = FlyweightNumber;
The problem is that when I'm not using a FlyweightNumber value anymore it is still in memory, stored in this Map. 问题是,当我不再使用FlyweightNumber值时,它仍在内存中,并存储在此Map中。
Since WeakMap and WeakSet are supposed to let garbage colector clear it if it is not used anymore, how could I write a constructor to return the object in the WeakSet or WeakMap or create a new object if it is not stored anymore? 由于如果不再使用WeakMap和WeakSet,应该让垃圾收集器将其清除,那么我该如何编写一个构造函数以返回WeakSet或WeakMap中的对象,或者如果不再存储该对象,则创建一个新对象?
You're looking for a soft reference to implement your number cache. 您正在寻找实现号码缓存的软参考 。 Unfortunately, JS doesn't have these. 不幸的是,JS没有这些。
And its WeakMap
doesn't create weak references either, it's an ephemeron actually. 而且它的WeakMap
也不会创建弱引用,实际上是一个星历表 。 It does not allow you to observe whether an object has been collected. 它不允许您观察是否已收集对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.