The super
keyword is used to call the constructor of its parent class to access the parent's properties and methods.
Tip: To understand the "inheritance" concept (parent and child classes) better, read our JavaScript Classes Tutorial.
Create a class named "Model" which will inherit the methods from the "Car" class, by using the extends
keyword.
By calling the super()
method in the constructor method, we call the parent's constructor method and gets access to the parent's properties and methods:
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();
super
is an ECMAScript6 (ES6) feature.
ES6 (JavaScript 2015) is supported in all modern browsers:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
super
is not supported in Internet Explorer 11 (or earlier).
super(
arguments); // calls the parent constructor (only inside the constructor)
super.
parentMethod(
arguments); // calls a parent method
JavaScript Version: | ECMAScript 2015 (ES6) |
---|
JavaScript Tutorial: JavaScript Classes
JavaScript Tutorial: JavaScript ES6 (EcmaScript 2015)
JavaScript Reference: The extends Keyword
JavaScript Reference: The constructor() method
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!