JavaScript Class static keyword
- Pagina precedente extends
- Pagina successiva super
- Torna alla pagina superiore Manuale di Referenza Class JavaScript
Definition and Usage
static
The keyword for defining static methods in a class definition.
Static methods are directly on the class (in the example above, Car
) call, without creating an instance/object of the class (mycar
)
Instance
Example 1
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(); //Do not call on the 'mycar' object: //document.getElementById("demo").innerHTML = mycar.hello(); //Will cause an error
Example 2
If you want to use the mycar object inside a static method, you can send it as a parameter:
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);
语法
static methodName()
技术细节
JavaScript版本: | ECMAScript 2015 (ES6) |
---|
浏览器支持
Keyword | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
static | 49.0 | 13.0 | 45.0 | 9.0 | 36.0 |
相关页面
JavaScript教程:Classe JavaScript
JavaScript教程:JavaScript ES6 (EcmaScript 2015)
Manuale di riferimento JavaScript:Metodo constructor()
- Pagina precedente extends
- Pagina successiva super
- Torna alla pagina superiore Manuale di Referenza Class JavaScript