【发布时间】: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