Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 761
Amir Azarbashi Avatar asked Dec 28 '17 18:12

Amir Azarbashi


People also ask

What is static method in ES6?

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.

What is static property in JavaScript?

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.

How do you declare private and static variables in classes in JavaScript?

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.

How do you define a static class in typescript?

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.


2 Answers

class Game{    constructor(){} } Game.cards = [];  Game.cards.push(1); console.log(Game.cards); 

You can define a static variable like that.

like image 134
zagoa Avatar answered Sep 28 '22 02:09

zagoa


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.

like image 41
margaretkru Avatar answered Sep 28 '22 02:09

margaretkru