Create a Car class, and then create an object called "mycar" based on the Car class:
class Car {
constructor(brand) { // Constructor
this.carname = brand;
}
}
mycar = new Car("Ford");
More "Try it Yourself" examples below.
The constructor()
method is a special method for creating and initializing objects created within a class.
The constructor()
method is called automatically when a class is initiated, and it has to have the exact name "constructor", in fact, if you do not have a constructor method, JavaScript will add an invisible and empty constructor method.
Note: A class cannot have more than one constructor() method. This will throw a SyntaxError
.
You can use the super()
method to call the constructor of a parent class (see "More Examples" below).
constructor()
is an ECMAScript6 (ES6) feature.
ES6 (JavaScript 2015) is supported in all modern browsers:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
constructor()
is not supported in Internet Explorer 11 (or earlier).
constructor(
parameters)
JavaScript Version: | ECMAScript 2015 (ES6) |
---|
To create a class inheritance, use the extends
keyword.
A class created with a class inheritance inherits all the methods from another class:
Create a class named "Model" which will inherit the methods from the "Car" class:
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}
class Model extends Car {
constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}
mycar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = mycar.show();
The super()
method refers to the parent class.
By calling the super()
method in the constructor method, we call the parent's constructor method and get access to the parent's properties and methods.
JavaScript Tutorial: JavaScript Classes
JavaScript Tutorial: JavaScript ES6 (EcmaScript 2015)
JavaScript Reference: The extends Keyword
JavaScript Reference: The super Keyword
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!