Kns
Kns

Reputation: 25

Set method when instance is created

Is there any way to execute the set method when an instance is created?. I have this piece of code:

class CoffeeMachine {
  _power;
  
  constructor(power) {
    this._power = power;
  }
  
  set power(value) {
    if (value < 100) {
      this._power = 100;
    }
  }
  
  get power() {
    return this._power;
  }
}

// create the coffee machine
let machine = new CoffeeMachine(90);
console.log(machine)

I know that if I set "power" to public the setter is executed but I need it to be a protected property. Power is still 90 even it's less than 100, so it doesn't work. Any tips?

Upvotes: 1

Views: 61

Answers (2)

Gavin Morrow
Gavin Morrow

Reputation: 769

You have to change the this._power = power; in the constructor to this.power = power;, because there isn't a setter placed on _power. If you set power, it should call the setter.

class CoffeeMachine {
  _power;
  
  constructor(power) {
    this.power = power; // ***
  }
  
  set power(value) {
    if (value < 100) {
      this._power = 100;
    }
  }
  
  get power() {
    return this._power;
  }
}

// create the coffee machine
let machine = new CoffeeMachine(90);
console.log(machine)

As a side note, you could make _power private by making it #power (see the MDN Docs for more info).

Upvotes: 1

epascarello
epascarello

Reputation: 207527

I am guessing your setter logic is not supposed to be over the power level of 100. You are not setting the value when the cause is valid. You should be setting power in the constructor and not the private property directly.

I added logging to show the things being called.

class CoffeeMachine {
  #power;
  
  constructor(power) {
    console.log(`contructor called with value ${power}`);
    this.power = power;
  }
  
  set power(value) {
    console.log(`setter called with ${value}`);
    this.#power = value > 100 ? 100 : value;
    console.log(`power set to ${this.#power}`);
  }
  
  get power() {
    console.log(`getter called, returning ${this.#power}`);
    return this.#power;
  }
}

// create the coffee machine
let machine = new CoffeeMachine(90);
console.log(1, machine.power);

machine.power = 1000;
console.log(2, machine.power);

If you do not want a public setter, then do not add one.

class CoffeeMachine {
  #power;
  
  constructor(power) {
    console.log(`contructor called with value ${power}`);
    this.#updatePower(power);
  }
  
  #updatePower(value) {
    console.log(`setter called with ${value}`);
    this.#power = value > 100 ? 100 : value;
    console.log(`power set to ${this.#power}`);
  }
  
  get power() {
    console.log(`getter called, returning ${this.#power}`);
    return this.#power;
  }
}

// create the coffee machine
let machine = new CoffeeMachine(90);
console.log(1, machine.power);

machine.power = 1000;  // ignored
console.log(2, machine.power);

Upvotes: 3

Related Questions