how to define a static property in the ES6 classes [duplicate]

你。 提交于 2019-12-04 09:54:32

问题


I want to have a static property in an ES6 class. This property value is initially an empty array.

    class Game{

        constructor(){
           // this.cards = [];
        }

        static cards = [];
    }
    
    Game.cards.push(1);

    console.log(Game.cards);

How can I do it?


回答1:


One way of doing it could be like this:

let _cards = [];
class Game{
    static get cards() { return _cards; }
}

Then you can do:

Game.cards.push(1);
console.log(Game.cards);

You can find some useful points in this discussion about including static properties in es6.




回答2:


class Game{
   constructor(){}
}
Game.cards = [];

Game.cards.push(1);
console.log(Game.cards);

You can define a static variable like that.



来源:https://stackoverflow.com/questions/48012663/how-to-define-a-static-property-in-the-es6-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!