目录

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.

Try it Yourself »


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:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

static is not supported in Internet Explorer 11 (or earlier).


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);

Try it Yourself »


Related Pages

JavaScript Tutorial: JavaScript Classes

JavaScript Tutorial: JavaScript ES6 (EcmaScript 2015)

JavaScript Reference: The constructor() method