繁体   English   中英

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

[英]Javascript: Use object in ES6 class as member and static object

我最近遇到了一个问题。

我有一个用 ES6 编写的 javascript 类。

应该有一个静态对象。 该对象也应该可用于类方法,而无需对其进行两次定义。

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

有什么办法吗?


//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 Status {
....
}

Status.types = {
    ...
}

似乎不需要将types作为函数。 这有效:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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