1. Use extends to implement subclass to inherit parent class
- Why should we implement a subclass to inherit the parent?
The following code is the same as the code in the constructor in Chinese and American. If we want to build more such classes, the code will be very bloated, so we can create a parent class and let the child class inherit the content of the parent class.
Original code:
class American { constructor (name, age) { this.name = name; this.age = age; } } const a1 = new American('Bob', 25); class Chinese { constructor (name, age) { this.name = name; this.age = age; } } const c1 = new Chinese('Xiao Wang', 26);
Use the extends keyword to implement the inherited Code:
//This is the parent class. class Person { constructor (name, age) { this.name = name; this.age = age; } } //This is a subclass. class American extends Person{ } const a1 = new American('Bob', 25); //This is a subclass. class Chinese extends Person{ } const c1 = new Chinese('Xiao Wang', 26);
-
A subclass inherits the Example method:
//This is the parent class. class Person { constructor (name, age) { this.name = name; this.age = age; } say (h) { console.log(h) } } //This is a subclass. class American extends Person{ } const a1 = new American('Bob', 25); a1.say('hello')//hello //This is a subclass. class Chinese extends Person{ } const c1 = new Chinese('Xiao Wang', 26); c1.say('Hello')//Hello
II. Use of super function
-
What is super
super is a function. super in a subclass is a reference to constructor in the parent class. -
When do I need to use super
When a subclass inherits its parent class through extensions, and the subclass needs to have its own unique properties, it needs to give priority to the super function within the constructor constructor of the subclass, and it must give priority to * * (syntax specification).
For example, in the following example, when the Chinese inherit the parent class, they also have a unique ID number:
//This is the parent class. class Person { constructor (name, age) { this.name = name; this.age = age; } say (h) { console.log(h) } } //This is a subclass. class American extends Person{ } const a1 = new American('Bob', 25); a1.say('hello') //This is a subclass. class Chinese extends Person{ constructor (name, age, IDcard) { super(name, age); this.IDcard = IDcard; } } const c1 = new Chinese('Xiao Wang', 26, '220225xxxxxxxxxxx'); c1.say('Hello') console.log(c1)//Chinese {name: "Xiao Wang", age: 26, ID: "220225xxxxxxxx"}
At this point, the class class tutorial in ES6 is over. If you don't understand this article, please refer to the previous class class usage and tutorial in ES6 (basic chapter).