Search code examples
javascriptclassoopgetter-setterencapsulation

How to properly implement getter/setter functionality, either for both a property's `get` and `set`, or for two methods and a property's `get`?


I have a logic that need to reactively run some function
if a this.variableName is changed inside or outside the class

the problem is with this logic, getter doesn't work, and I get undefined.

not only this, but also maximum stack error.
because is like: set the this inside the setter, that re-set the this, that re-call another time the setter, that set the this, and so on... (but this isn't what I meant)


Semplified version, without parameters, and so, just the minimal example of the bug.

class MyClass {
  constructor() {
     this.isOn = false;
  }

  set isOn(value) {
    this.isOn = value;
    // another functions that do stuff. you can put here a bunch of console.logs if you want just for the demo
  }

  // the idea is another, but i will show you the simpliest method, I could imagine, just to make you get the idea
  
  turnOn() {
     this.isOn = true;
  }
 
  turnOff() {
     this.isOn = false;
  }

  // using this approach, 
  // I don't need to copy paste the same functions in this 2 methods, 
  // so I just need to care about the var, 
  // without using a imperative approach, 
  // but a declarative approach
}

I know we can use _isOn,
but this is literally the opposite of what we want,
because I want the setter to be the same name of the getter,
and still do the logic on setter.

hope you get my idea. thanks


Solution

  • You can use private properties

    class MyClass {
      #isOn = false;
    
      set isOn(value) {
        this.#isOn = value;
      }
      
      get isOn() {
        return this.#isOn
      }
    
      turnOn() {
         this.isOn = true;
      }
     
      turnOff() {
         this.isOn = false;
      }
    }
    
    const x = new MyClass
    
    x.isOn = true
    
    console.log(x.isOn)
    
    // This will throw an error:
    // console.log(x.#isOn)