So I have a simple Javascript class
class MyClass {
constructor(x) {
this.x = x === undefined ? 0 : x;
}
get x() {
return this.x;
}
}
When a MyClass is created, I want it's x to be set to the value passed in as a parameter. After this, I do not want it to be able to be changed, so I have intentionally not made a set x() method.
However, I guess I must be missing something fundamental, as this is giving me the "Cannot set property ... which only has getter" error.
How do I assign a value to x without creating a setter method?
this.xin the getter will be understood as a function call to the getter, meaning infinite recursion.readonlyto be set once in the constructor only.set(x) { if (this.x === undefined ) { this.x = x; } }and in the constructor onlythis.x = x;should suffice.