简体   繁体   中英

Javascript: Use object in ES6 class as member and static object

I have run into a issue lately.

I have a javascript class written in ES6.

There should be a static object. This object should also be available for class methods without defining it twice.

I tried to set the class member (property) to the static member in the constructor, but it throws an error:

Is there any way?


//Benötigt Bibliotheken: W3.css, W3.js

'use strict';

class Status {
    constructor(type, headerText, message){
        this.type = type;
        statusHeader.innerHTML = headerText;
        statusText.innerHTML = message;
        this.types = Status.types;  //set the instance member to the static member.

        this.setColor();
        this.setStyle();
    }

    setStyle() {
        //Alle Farbklassen entfernen.
        w3.removeClass('#' + status.id, Object.values(this.colors).join(" ") );

        //Farbklasse setzen.
        w3.addClass( '#' + status.id, this.color );
    }

    show() {
        w3.show('#' + status.id);
    }

    hide(){
        w3.hide('#' + status.id);
    }

    setColor() {
        switch(this.type){
            case this.types.info:
                this.color = this.colors.blue;
                break;
            case this.types.success:
                this.color = this.colors.green;
                break;
            case this.types.warning:
                this._color = this.colors.yellow;
                break;
            case this.types.error:
                this._color = this.colors.red;
                break;
        }
    }

    static colors(){ 
        return {
            'blue': 'w3-light-blue',
            'green': 'w3-light-green',
            'yellow': 'w3-light-yellow',
            'red': 'w3-light-red'
        };
    }
    static types(){
        return {
            'info': info,
            'success': success,
            'warning': warning,
            'error': error
        };
    }

/*  get colors(){ return this.colors; }

    get types(){ return this.types; } */
}

//Test class
alert(Status.types.info);   //Alert: 'undefined'
alert(new Status('info', 'Header', 'Message').types.info);  //Error: Status.js:19 Uncaught TypeError: Cannot convert undefined or null to object

After the class definition add static members..

class Status {
....
}

Status.types = {
    ...
}

There doesn't seem to be any need for types to be a function. This works:

 class Status { constructor() { this.types = Status.types; } static types = { 'info': 'info', }; } const foo = new Status(); console.log(foo.types);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM