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?

4
  • set objects(...) {...} Commented Apr 6, 2017 at 14:40
  • oops, sorry, that was a typo in the post... The error still persists :-( Commented Apr 6, 2017 at 14:41
  • you'll want a return statement in your getter also... Commented Apr 6, 2017 at 14:43
  • Sorry for all the typos, my original code is way more complex so I wrote this example from scratch without testing it... Commented Apr 6, 2017 at 14:45

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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...
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.