可以制作类/实例范围的getter& JS的二传手?

时间:2017-02-17 00:30:01

标签: javascript ecmascript-6

我正在尝试使用大量的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

}

1 个答案:

答案 0 :(得分:1)

是的,停止制作单身人士。和吸气剂。和塞特斯。

class GameData {
  constructor() {
    this.level = 0;
    this.score = 0;
  }
}

export default new GameData();