How do I use a static variable in ES6 class?

前端 未结 5 620
故里飘歌
故里飘歌 2021-02-05 04:11

I\'m trying to use a static variable in es6. I\'d like to declare a static variable count in Animal class and increase it. However, I couldn\'t declare

5条回答
  •  感动是毒
    2021-02-05 04:50

    Static class-side properties and prototype data properties must be defined outside of the ClassBody declaration.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

    class Animal {
    
      static increaseCount() {
        Animal.count += 1;
      }
    
      static getCount() {
        return Animal.count;
      }
    }
    
    Animal.count = 0;
    
    Animal.increaseCount();
    console.log(Animal.getCount()); // undefined

提交回复
热议问题