2

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.

0

1 Answer 1

5

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.