React ES6 類
Classes
ES6 引入了類(classes)。
類(class)是一種函式,但它不使用 `function` 關鍵字來宣告,而是使用 `class` 關鍵字,並且屬性在 `constructor()` 方法中分配。
示例
一個簡單的類建構函式
class Car {
constructor(name) {
this.brand = name;
}
}
請注意類名稱的大小寫。我們以大寫字母“Car”開頭。這是類的標準命名約定。
現在您可以使用 Car 類建立物件
示例
基於 Car 類建立一個名為“mycar”的物件
class Car {
constructor(name) {
this.brand = name;
}
}
const mycar = new Car("Ford");
注意:建構函式在初始化物件時會自動呼叫。
類中的方法
您可以在類中新增自己的方法
示例
建立一個名為“present”的方法
class Car {
constructor(name) {
this.brand = name;
}
present() {
return 'I have a ' + this.brand;
}
}
const mycar = new Car("Ford");
mycar.present();
如上例所示,您可以透過引用物件的 `方法名()` 來呼叫方法(引數將放在括號內)。
類繼承
要建立類繼承,請使用 extends
關鍵字。
透過類繼承建立的類繼承了另一個類的所有方法
示例
建立一個名為 "Model" 的類,它將繼承 "Car" 類的方法
class Car {
constructor(name) {
this.brand = name;
}
present() {
return 'I have a ' + this.brand;
}
}
class Model extends Car {
constructor(name, mod) {
super(name);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model
}
}
const mycar = new Model("Ford", "Mustang");
mycar.show();
super()
方法指向父類。
透過在建構函式方法中呼叫 `super()` 方法,我們可以呼叫父類的建構函式方法,並訪問父類的屬性和方法。
要了解更多關於類的資訊,請檢視我們的 JavaScript 類 部分。