Cannot Set Property ... Which Only Has Getter (javascript es6)

There are a couple problems here.

When you make a getter via get x() you are causing this.x to result in calling the getter, which will recurse indefinitely due to your get x() doing this.x.

Replace your references to this.x with this._x in this code like this:

class MyClass {
    constructor(x) {
        this._x = x === undefined ? 0 : x;
    }

    get x() {
        return this._x;
    }
}

Now your encapsulated x which is now _x will not be confused for a call to the getter via this.x.


If you want to create an immutable property a within your class definition, this os one way to do so with the method JavaScript gives is to do this (using Object.defineProperty()).

class MyClass {
  constructor(x) {
    Object.defineProperty(this, 'a', {
      enumerable: false,
      configurable: false,
      writable: false,
      value: x || 'empty'
    });
  }

}
let o = new MyClass('Hello');

console.log(o.a);
o.a = 'Will not change';
console.log(o.a);