How do I use a static variable in ES6 class?

前端 未结 5 613
故里飘歌
故里飘歌 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 05:04

    you can use closures to simulate static variables

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

提交回复
热议问题