JavaScript Class static
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.
Description
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
static
is an ECMAScript6 (ES6) feature.
ES6 (JavaScript 2015) is supported in all modern browsers since June 2017:
Chrome 51 | Edge 15 | Firefox 54 | Safari 10 | Opera 38 |
May 2016 | Apr 2017 | Jun 2017 | Sep 2016 | Jun 2016 |
static
is not supported in Internet Explorer.
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