Search code examples
javascriptecmascript-6getter-settergetteres6-class

JavaScript ES6 class with getters only


I would like to ask, in ES6 how can I use getters only without setters (readOnly) properties? Why is Webstorm telling me that this is an error?

Here is my code:

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;
    }

}

I had put //noinspection JSUnresolvedVariable to suppress the warning. But there should be better solution than this.


Solution

  • It seems that you're assigning the values on the constructor to the getters instead of the backing fields prefixed with underscore.

    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;
    [..]
    

    In case you're not doing it already, you should declare your backing fields before using them.