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?
Static methods are often used to create utility functions for an application.” In other words, static methods have no access to data stored in specific objects. Note that for static methods, the this keyword references the class. You can call a static method from another static method within the same class with this.
The static keyword defines a static method or property for a class, or a class static initialization block (see the link for more information about this usage). Neither static methods nor static properties can be called on instances of the class. Instead, they're called on the class itself.
To call the static method we do not need to create an instance or object of the class. Static variable in JavaScript: We used the static keyword to make a variable static just like the constant variable is defined using the const keyword. It is set at the run time and such type of variable works as a global variable.
A static class can be defined as a sealed class that cannot be inherited besides being inherited from an Object. static class cannot be instantiated, which means you cannot create the instance variable from the Static Class reference.
class Game{ constructor(){} } Game.cards = []; Game.cards.push(1); console.log(Game.cards);
You can define a static variable like that.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With