【问题标题】:Javascript: Use object in ES6 class as member and static objectJavascript:使用 ES6 类中的对象作为成员和静态对象
【发布时间】:2019-12-18 13:34:10
【问题描述】:

我最近遇到了一个问题。

我有一个用 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

【问题讨论】:

  • Status.types() 有什么问题?你为什么坚持,this.types() 必须工作?
  • types 是一个静态方法。您需要将其命名为this.types = Status.types()。不知道你为什么要这样做

标签: javascript class static instance member


【解决方案1】:

types 似乎不需要成为一个函数。这有效:

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

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


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

【讨论】:

  • 请注意,静态属性尚未得到广泛支持。适用于 V8,但并非无处不在。
  • 哇,你们太棒了。 mbojko 的解决方案成功了!太好了。
【解决方案2】:

类定义后添加静态成员..

class Status {
....
}

Status.types = {
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    相关资源
    最近更新 更多