一、使用 extends 實現子類繼承父類
- 爲什麼要實現子類繼承父類?
下面的代碼兩個類American和Chinese中的constructor裏面的代碼是一樣的,如果我們要建立更多這樣的類,這樣的代碼就會十分臃腫,所以我們可以創建一個父類,讓子類去繼承父類的內容;
原代碼:
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('小王', 26);
使用extends關鍵字實現繼承後的代碼:
//這是父類
class Person {
constructor (name, age) {
this.name = name;
this.age = age;
}
}
//這是子類
class American extends Person{
}
const a1 = new American('Bob', 25);
//這是子類
class Chinese extends Person{
}
const c1 = new Chinese('小王', 26);
-
子類繼承父類的實例方法:
//這是父類 class Person { constructor (name, age) { this.name = name; this.age = age; } say (h) { console.log(h) } } //這是子類 class American extends Person{ } const a1 = new American('Bob', 25); a1.say('hello')//hello //這是子類 class Chinese extends Person{ } const c1 = new Chinese('小王', 26); c1.say('你好')//你好
二、super函數的使用
-
super是什麼
super是一個函數,子類中的super就是父類中constructor構造器的一個引用; -
什麼時候需要使用super
當子類通過extends繼承父類後,子類需要有自己 獨有 的屬性時,就需要在子類的constructor構造器內部 優先優先優先 使用super函數,必須要優先使用**(語法規範);
例如下面的例子,中國人在繼承了父類的同時,還有了獨有的身份證號碼:
//這是父類
class Person {
constructor (name, age) {
this.name = name;
this.age = age;
}
say (h) {
console.log(h)
}
}
//這是子類
class American extends Person{
}
const a1 = new American('Bob', 25);
a1.say('hello')
//這是子類
class Chinese extends Person{
constructor (name, age, IDcard) {
super(name, age);
this.IDcard = IDcard;
}
}
const c1 = new Chinese('小王', 26, '220225xxxxxxxxxxx');
c1.say('你好')
console.log(c1)//Chinese {name: "小王", age: 26, ID: "220225xxxxxxxxxxx"}
至此,es6中的class類的教程就結束了,如果這篇文章有看不懂的地方,請翻看上一篇 ES6中class類使用方法及教程(基礎篇)