Sparsed Arrays与地图对象

时间:2018-03-02 20:26:11

标签: javascript domain-driven-design value-objects

link有一篇文章说: “避免密钥不是增量数字的稀疏数组。其中没有每个元素的稀疏数组都是哈希表。“

使用地图对象会更好吗?

我使用这种数组来存储由它编制的每个对象的ID。我用它来创建Value Objects(DDD)的单例。

我正在创造这种对象:

const ValueObject = (function(){

    const instances = [];

    class ValueObject{

       constructor(value){

           Object.defineProperty(this, 'value', {
               value: value
           });

        if(!instances[value]){
            instances[value] = this;
        }
        else {
            return instances[value];
        }

       }

       toString(){
           return this.value;
       }

       valueOf(){
           return this.value;
       }

    }

    return ValueObject;

})();

写下面的内容会更好吗?

const ValueObject = (function(){

    const instances = new Map();

    class ValueObject{

       constructor(value){

           Object.defineProperty(this, 'value', {
               value: value
           });

           if(!instances.get(value)){
               instances.set(value, this);
           }
           else {
               return instances.get(value);
           }

       }

       toString(){
           return this.value;
       }

       valueOf(){
           return this.value;
       }

    }

    return ValueObject;

})();

0 个答案:

没有答案
相关问题