Gro*_*nov 3 javascript getter getter-setter ecmascript-6 es6-class
我想问一下,在ES6中如何才能在没有setter(readOnly)属性的情况下使用getter?为什么Webstorm告诉我这是一个错误?
这是我的代码:
class BasePunchStarter {
constructor(id,name,manufacturer,description,genres,targetPrice) {
if (new.target==BasePunchStarter) {
throw new TypeError("BasePunchStarter class cannot be instantiated directly!");
}
if (typeof id =="number") {
// noinspection JSUnresolvedVariable
this.id = id;
} else throw new TypeError("ID must be a number!");
if (typeof name=="string") {
// noinspection JSUnresolvedVariable
this.name = name;
} else throw new TypeError("Name must be a string!");
if(typeof manufacturer=="string") {
// noinspection JSUnresolvedVariable
this.manufacturer = manufacturer;
} else throw new TypeError("Manufacturer must be a string!");
if (typeof description=="string") {
// noinspection JSUnresolvedVariable
this.description = description;
} else throw new TypeError("Description must be a string!");
if(typeof genres=="Object") {
// noinspection JSUnresolvedVariable
this.genres=genres;
} else new TypeError("Genres must be an Array of strings!");
if (typeof targetPrice=="number") {
// noinspection JSUnresolvedVariable
this.targetPrice = targetPrice;
} else new TypeError("Target price must be a number!");
this.accumulatedMoney=0;
}
get accumulatedMoney() {
return this._accumulatedMoney;
}
set accumulatedMoney(money) {
this._accumulatedMoney=money;
}
get id() {
return this._id;
}
get name() {
return this._name;
}
get manufacturer() {
return this._manufacturer;
}
get description() {
return this._description;
}
get genres() {
return this._genres;
}
get targetPrice() {
return this._targetPrice;
}
}
Run Code Online (Sandbox Code Playgroud)
我曾//noinspection JSUnresolvedVariable压制警告.但应该有比这更好的解决方案.
您似乎将构造函数的值分配给getter而不是前缀为下划线的支持字段.
constructor(id,name,manufacturer,description,genres,targetPrice){
if(new.target==BasePunchStarter){
throw new TypeError("BasePunchStarter class cannot be instantiated directly!");
}
if(typeof id =="number") {
// use the backing field instead.
this._id = id;
[..]
Run Code Online (Sandbox Code Playgroud)
如果您还没有这样做,您应该在使用之前声明您的支持字段.
| 归档时间: |
|
| 查看次数: |
2952 次 |
| 最近记录: |