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
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.
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.
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.
Static class methods are defined on the class itself. You cannot call a static method on an object, only on an object class.
You can use static getter:
class HasStaticValue {
static get MIN() {
return 10;
}
}
console.log(HasStaticValue.MIN);
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