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?
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.
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