Reputation: 591
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?
Upvotes: 0
Views: 1826
Reputation: 221
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
Upvotes: 3
Reputation: 350147
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.
Upvotes: 2