Red
Red

Reputation: 7299

set a getter/setter on class variable JavaScript

I have a class which looks like below:

export default class Car {
    brand = '';

    color = '';

    fuel = '';

    constructor(car) {
        ...
    }
}

How can I set a setter on the class variables?

So for example

export default class Car {
    brand = '';

    color = '';

    fuel = '';

    set brand(brand) {
        ...
    }

    get brand() {
        return ...;
    }

    get color(color) {
        return ...;
    }

    set color(color) {
        ...
    }
}

I tried to use the above, however, it doens't work.

class Car {
    brand = '';

    color = '';
  
  constructor(car) {
    this.brand = car.brand;
    this.color = car.color;
  }
  
  set brand(val) {
    // It should alert Audi.
    alert(val);
  }
}

let car = new Car({brand: 'BMW', color: 'white'});
car.brand = 'Audi';

It doens't alert the value I am setting on brand.

Upvotes: 2

Views: 2188

Answers (1)

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

The problem lays in the naming convention, both the setter and public property are the same, so when setting it you don't actually use the custom setter. If you were to change the name it would work ex.

class Car {
  _brand = '';
  _color = '';

  constructor(car) {
    this._brand = car.brand;
    this._color = car.color;
  }

  set brand(val) {
    this._brand = val;
    alert(val);
  }
  
  get brand() {
    return this._brand;
  }
}

let car = new Car({
  brand: 'BMW',
  color: 'white'
});

car.brand = 'Audi';

console.log(car.brand)

Upvotes: 5

Related Questions