JavaScript Class (class)staticKeyword

JavaScript 类(class)JavaScript Class (class)


Examples

Examples

The following example creates a class "Example" and a static method hello():

class Example { constructor(name) { this.name = name; } static hello() { return "Hello!!"; } } let noob = new Example("Example Tutorial"); //Can call the 'hello()' method in the class document.getElementById("demo").innerHTML = Example.hello(); //Cannot call static methods through an instantiated object // document.getElementById("demo").innerHTML = noob.hello(); //The above code will throw an error

Try it Yourself »


Definition and Usage

Classes define static methods using the static keyword.

Static methods are called directly on the class, and cannot be called on instances of the class.

Static methods are often used to create utility functions.

Syntax

static methodName()

Technical Details

JavaScript Version: ECMAScript 2015 (ES6)

Browser Support

static is an ECMAScript6 (ES6) feature.

ES6 (JavaScript 2015) is supported by all current mainstream browsers.

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

Internet Explorer 11 or older versions of IE do not support the static keyword.


JavaScript 类(class)JavaScript Class (class)

Other Extensions