ES6 Classes - Updating Static Properties

后端 未结 3 812
再見小時候
再見小時候 2020-12-06 00:58

I am trying to figure out alternative ways to set a static (or class) property an ES6 Class and then change it after new instances of the class are created.

For exa

3条回答
  •  一个人的身影
    2020-12-06 01:49

    This works for me for static properties.

      class NeoGeo {
    
        constructor() {
    
        }
    
        static get topScore () {
          if (NeoGeo._topScore===undefined) {
            NeoGeo._topScore = 0; // set default here
          }
    
          return NeoGeo._topScore;
        }
    
        static set topScore (value) {
          NeoGeo._topScore = value;
        }
    
      }
    

    And your example:

      class NeoGeo {
    
        constructor() {
          NeoGeo.addInstance(this);
          console.log("instance count:" + NeoGeo.all.length);
        }
    
        static get all () {
    
          if (NeoGeo._all===undefined) {
            NeoGeo._all = [];
          }
    
          return NeoGeo._all;
        }
    
        static set all (value) {
          NeoGeo._all = value;
        }
    
        static addInstance(instance) {
          // add only if not already added
          if (NeoGeo.all.indexOf(instance)==-1) {
            NeoGeo.all.push(instance);
          }
        }
      }
    

    Note: In the getter you could also check for the existence of the property using the in keyword or the hasOwnProperty keyword.

        static get topScore () {
          if (!("_topScore" in NeoGeo)) {
            NeoGeo._topScore = 0; // set default here
          }
    
          return NeoGeo._topScore;
        }
    

    And using hasOwnProperty:

        static get topScore () {
          if (NeoGeo.hasOwnProperty("_topScore")==false) {
            NeoGeo._topScore = 0; // set default here
          }
    
          return NeoGeo._topScore;
        }
    

提交回复
热议问题