☰ See All Chapters |
JavaScript ES6 Static Members
Static properties are also called class properties or class variables. If a property's value never changes, it should be declared as static to ensure that it won't be redefined for each instance. If a property's value only changes when the constructor is called and doesn't depend on the instance, it should be made static. Static members can assess only static members, but static members can be accessed by anyone.
Static Properties
Properties can be made static by preceding the declaration with the static keyword. Visibility of static variables is similar to instance variables which depend on the access specifiers. However, most static variables are declared public since they must be available for users of the class. Static variables can be accessed by calling with the class name as below:
className.variableName |
Example
class Test { static fullName = "Manu Manjunatha"; static message = "Hello"; finalMessage; constructor(greet) { this.finalMessage = Test.message + Test.fullName + greet; } }
let fullName = Test.fullName; console.log(fullName); |
Static Methods
Methods can be made static by preceding the declaration with the static keyword. Static methods are invoked through the class name, not through an instance, can be accessed by calling with the class name as below:
className.methodName(); |
Example
class Test { static getFullName(firstName, lastName) { return firstName + " " + lastName; } } let fullName = Test.getFullName("Manu", "Manjunatha"); |
All Chapters