Tuesday, 13 April 2021

Using JS Class Setter & getter along with inline functions

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.



from Using JS Class Setter & getter along with inline functions

No comments:

Post a Comment