Search code examples
javascriptsetteres6-class

Setters for object arrays in ES6


I have a class that contains an array that is used to contain objects of a certain type.

class Test {
    constructor() {
      this.objects = [];
    }

    # Only objects with positive foobars should be returned
    get objects() { return this.objects.filter(o => o.foobar >= 0); }
}

I don't need any special treatment for setting values in the array, so I didn't write a set method. But now I get an error saying I cannot write to a property that only has a getter method. So I tried to reconstruct the default setter method like so:

set objects(k,v) { this.objects[k] = v; }
set objects[k](v) { this.objects[k] = v; }
set objects(v) { this.objects = v; }

But none of the above work. I simply want to be able to set values in the array as usual via this.objects[2] = foobar; How do I tell ES6 that?


Solution

  • You should name the object property and prototype's getter differently, otherwise the constructor will try to find the setter that corresponds to the prototype's (class's) getter when it does this.objects = ....

    class Test {
        constructor() {
          this.objects = [];
        }
    
        get positiveObjects() { this.objects.filter(o => o.foobar >= 0); }
    }
    

    NB: Your constructor method is named wrongly. It should be constructor, not construct. In the mean time you corrected it.