我有一堂课,如下所示:
export default class Car {
brand = '';
color = '';
fuel = '';
constructor(car) {
...
}
}
如何在类变量上设置设置器?
所以举个例子
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句