JavaScript Class static Keyword
❮ JavaScript Classes Reference
Example
Create a static method and call it on the class:
class Car {
constructor(brand) {
this.carname =
brand;
}
static hello() { // static method
return "Hello!!";
}
}
mycar = new Car("Ford");
//Call 'hello()' on
the class Car:
document.getElementById("demo").innerHTML
= Car.hello();
//and NOT on the 'mycar' object:
//document.getElementById("demo").innerHTML
= mycar.hello();
//this would raise an error.
Definition and Usage
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.
Browser Support
Keyword | |||||
---|---|---|---|---|---|
static | 49.0 | 13.0 | 45.0 | 9.0 | 36.0 |
Syntax
static methodName()
Technical Details
JavaScript Version: | ECMAScript 2015 (ES6) |
---|
More Examples
If you want to use the mycar object, inside the static method, you can send it as a parameter:
Example
Send "mycar" as a parameter:
class Car {
constructor(brand) {
this.carname =
brand;
}
static hello(x) {
return "Hello " +
x.carname;
}
}
mycar = new Car("Ford");
document.getElementById("demo").innerHTML
= Car.hello(mycar);
Related Pages
JavaScript Tutorial: JavaScript Classes
JavaScript Tutorial: JavaScript ES6 (EcmaScript 2015)
JavaScript Reference: The constructor() method
❮ JavaScript Classes Reference