Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add static attribute to ES6 class

We know very well that class of ES6 brought also : static, get as well as set features :

However , it seems that static keyword is reserved only for Methods :

class Person {

    // static method --> No error
    static size(){
    }   
  // static attribute --> with Error
    static MIN=10;
}

How to be able to write static attribute within ES6 class to have something like the static attribute MIN.

We know that we can add the following instruction after class definition :

Person.MIN=10; 

However , our scope is to find the way to write this instruction inside class block

like image 883
Abdennour TOUMI Avatar asked Jul 13 '16 22:07

Abdennour TOUMI


People also ask

What is static 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.

How do I create a static variable 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.

Which keyword's are required to create a static property within a class?

The static keyword defines static methods for classes. Static methods are called directly on the class ( Car from the example above) - without creating an instance/object ( mycar ) of the class.

Is there static class in JavaScript?

Static class methods are defined on the class itself. You cannot call a static method on an object, only on an object class.


1 Answers

You can use static getter:

class HasStaticValue {
  static get MIN() {
    return 10;
  }
}

console.log(HasStaticValue.MIN);
like image 82
Morteza Tourani Avatar answered Oct 11 '22 13:10

Morteza Tourani