Javascript:使用ES6中的对象class作为成员和静态对象

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

我最近 运行 遇到了一个问题。

我有一个javascriptclass用ES6写的

应该有一个静态对象。该对象也应该可用于 class 方法而无需定义它两次。

我试图在构造函数中将 class 成员 (属性) 设置为静态成员,但它抛出错误:

有什么办法吗?


//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

在 class 定义后添加静态成员..

class Status {
....
}

Status.types = {
    ...
}

types似乎没有必要成为函数。这有效:

class Status {
  constructor() {
    this.types = Status.types;
  }

  static types = {
    'info': 'info',
  };
}


const foo = new Status();
console.log(foo.types);