How do I use a static variable in ES6 class?

前端 未结 5 537
故里飘歌
故里飘歌 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

    To set a static variable, set it on the object Animal itself. As of now in Javascript you cannot directly declare static properties inside classes like you can declare static methods.

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

提交回复
热议问题