在 class 变量 JavaScript 上设置 getter/setter
set a getter/setter on class variable JavaScript
我有一个 class,如下所示:
export default class Car {
brand = '';
color = '';
fuel = '';
constructor(car) {
...
}
}
如何在 class 变量上设置 setter?
例如
export default class Car {
brand = '';
color = '';
fuel = '';
set brand(brand) {
...
}
get brand() {
return ...;
}
get color(color) {
return ...;
}
set color(color) {
...
}
}
我尝试使用上面的方法,但是它不起作用。
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';
它不会提醒我在 brand
上设置的值。
问题出在命名约定上,setter和public属性是一样的,所以设置的时候你实际上并没有使用自定义的setter.如果您要更改名称,它会起作用。
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)
我有一个 class,如下所示:
export default class Car {
brand = '';
color = '';
fuel = '';
constructor(car) {
...
}
}
如何在 class 变量上设置 setter?
例如
export default class Car {
brand = '';
color = '';
fuel = '';
set brand(brand) {
...
}
get brand() {
return ...;
}
get color(color) {
return ...;
}
set color(color) {
...
}
}
我尝试使用上面的方法,但是它不起作用。
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';
它不会提醒我在 brand
上设置的值。
问题出在命名约定上,setter和public属性是一样的,所以设置的时候你实际上并没有使用自定义的setter.如果您要更改名称,它会起作用。
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)