0

I'm currently trying to setup a class where the property is an array of another object (define by another class).

I'm using the set/get to manage the values. I also initialize them in the constructor.

what I want to achieve is adding inline function to this same property to make life easier overall. However, I feel like I'm using the wrong approach here.

class _MainObject {
    constructor(){
        this._property = [];
        this.property= {
            add(value, index){
                if (value.constructor.name !== '_SubObject'){
                    return;
                }

                this._property.splice(index, 0, value);
            },
            remove(value){
                if (value.constructor.name !== '_SubObject'){
                    return;
                }

                const index = this._property.findIndex((pId) => pId === value.id);
                this._property.splice(index, 1);
            }
        };
    }

    set property(value){
        if (Array.isArray(value)){
            value.map((el) => {
                if (el.constructor.name !== '_SubObject') return;
            });
            this._property = value;
        }
        //Tried a bunch of stuff here to assign the default object from above on the first initialization.
    }
    get property(){
        return this._property;
    }
}

Whenever the constructor initialize the property, it trigger the "set" and won't assign the functions to 'property' itself.

I want the actual data in obj._property but fetch by calling obj.property. I also want to be able to call obj.property.add().

This must be doable in some way and I just don't know how.

Ideally, I want to use ES5+ semantic.

Thanks in advance for any help provided.

Johnny Prescott
  • 183
  • 4
  • 17

1 Answers1

1

class Property {
    constructor(){
        this.value = [1,2,3];
    }

    add(x){
        this.value = [...this.value, x]
    }
}

class _MainObject {
    constructor(){
        this._property = new Property();
    }

    set property(value){
        if (Array.isArray(value)){
            this._property = value;
        }
    }
    get property(){
        return this._property;
    }

}

const a = new _MainObject()
console.log(a.property)
a.property.add(4)
console.log(a.property)

You need to wrap property into it's own class.

This is the only way to do this as you cannot have a getter and a function or property of the same name as explained here:

Is there a way to use the same name for both a setter method and class property?

Differentiate between property and method with same name

Can JS have getters and setters methods named same as property?

Function and variable with the same name

Vulwsztyn
  • 638
  • 3
  • 10