Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有WeakMap或WeakSet的Javascript Flyweight_Javascript_Weak References_Flyweight Pattern_Weakmap - Fatal编程技术网

带有WeakMap或WeakSet的Javascript Flyweight

带有WeakMap或WeakSet的Javascript Flyweight,javascript,weak-references,flyweight-pattern,weakmap,Javascript,Weak References,Flyweight Pattern,Weakmap,我想要一个Flyweight对象,因此我创建了一个对象,并将其实例存储在如下地图中: const FlyweightNumber = (function(){ "use strict"; const instances = new Map(); class FlyweightNumber{ constructor(number){ Object.defineProperty(this, 'number', {

我想要一个Flyweight对象,因此我创建了一个对象,并将其实例存储在如下地图中:

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;
问题是,当我不再使用FlyweightNumber值时,它仍然在内存中,存储在这个映射中

既然WeakMap和WeakSet应该让垃圾收集器在不再使用的情况下清除它,那么我如何编写构造函数来返回WeakSet或WeakMap中的对象,或者在不再存储的情况下创建一个新对象呢?

您正在寻找实现数字缓存的方法。不幸的是,JS没有这些


它的弱映射也不会创建弱引用,它实际上是一个。它不允许您观察对象是否已被收集。

您不能。:/。。不要覆盖全局数字函数。@Bergi hahahaha我写这个作为例子,忘记了数字已经存在了。。。。改变了这个例子