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.
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.
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).
static
methodName()
JavaScript Version: | ECMAScript 2015 (ES6) |
---|
If you want to use the mycar object, inside the 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);
JavaScript Tutorial: JavaScript Classes
JavaScript Tutorial: JavaScript ES6 (EcmaScript 2015)
JavaScript Reference: The constructor() method
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!