0

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?

DP.
  • 581
  • 4
  • 15

2 Answers2

3

You can't write the objects in objects in getter. It may cause maximum call. I advice you to write in this way.

class Test {
  construct() {
    this.objects = [];
  }
  get legalobjects() { 
    return this.objects.filter(o => o.foobar >= 0);
  }
}

In which way you can set object as you want

To-xic
  • 211
  • 2
  • 4
2

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • OK, thank you, I didn't think of using a different name for the getters and setters than the original property name. This is different in Ruby... – DP. Apr 06 '17 at 14:48
  • Note that the plain property you assign in the constructor is not a setter. A setter can be defined with the `set` keyword, much like `get`, but it would be used to completely replace the current array with a new one. There are many other ways to deal with this, for instance by [extending Array](http://stackoverflow.com/questions/11337849/ways-to-extend-array-object-in-javascript). – trincot Apr 06 '17 at 14:56