简体   繁体   English

在 class 变量 JavaScript 上设置 getter/setter

[英]set a getter/setter on class variable JavaScript

I have a class which looks like below:我有一个 class 如下所示:

export default class Car {
    brand = '';

    color = '';

    fuel = '';

    constructor(car) {
        ...
    }
}

How can I set a setter on the class variables?如何在 class 变量上设置设置器?

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 .它不会提醒我在brand上设置的价值。

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.问题在于命名约定,setter 和 public 属性是相同的,所以在设置它时你实际上并没有使用自定义 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM