我希望问一下,在ES6中,如何使用只有getter没有setter(只读)的属性?为什么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;
}
}
我曾经使用//noinspection JSUnresolvedVariable
来抑制警告,但应该有更好的解决方案。
===
。另外,作为一个坚实的编程点,使构造函数抛出异常是一个非常糟糕的计划。那不是构造函数的责任。如果您有类型要求,请确保传入已经验证过的数据(无论如何都应该这样做),或者使用像TypeScript这样的东西,以便获得内置的类型安全性。 - Mike 'Pomax' Kamermansif(typeof genres=="Object"){
中,应该使用小写的"object"
。 - A. L. Flanagan