我正在尝试使用大量的getter和setter在JS中实现一个单例类。如果我可以为所有吸气剂和放大器定义原型/父母,那将会更方便。这个类中的setter,因为他们都需要在返回值
之前尝试初始化单例export class GameData {
constructor() {
this._level = 0;
this._score = 0;
}
static _init() {
if (!GameData._inst) {
GameData._inst = new GameData();
}
}
static clear() {
GameData._inst = null;
}
/*
Properties
I do not want to call GameData.init() on every property, any way to only do this once?
*/
static get level() {
GameData._init();
return GameData._inst._level;
}
static set level(val) {
GameData._init();
GameData._inst._level = val;
}
static get score() {
GameData._init();
return GameData._inst._score;
}
static set score(val) {
GameData._init();
GameData._inst._score = val
}
答案 0 :(得分:1)
class GameData {
constructor() {
this.level = 0;
this.score = 0;
}
}
export default new GameData();