uncategorized

類別(Classes)

在 ES6 以前,想要簡化相同程式碼,必須用 prototype 原型來達到類與類繼承,ES6 引入了類別(Class)作為 JavaScript 現有原型程式(prototype-based)的語法糖,提供了一個更簡潔的語法來建立物件與處理繼承。

類別(Classes)實際上是一種特別的函數,就跟你可以定義函數敘述和函數宣告一樣。透過 Class 建立物件,將兩個或多個物件的相同結構抽取出來變成一個模板,再依照模版複製出其他相似物件,這使我們不必再寫重複的程式碼。

要建立一個新的類別,必須用關鍵字class,如下所示,我們建立一個名為 Person 的類別,在此類別可為它建立屬性與方法。

1
2
3
4
class Person {      //注意 class 為小寫,Person 首字大寫
name: 'George' //建立 name 屬性
call: = () => {} //建立 call 方法
}

現在我們來改寫一下上面的程式碼,我們加入 class 另一個功能constructor,它代表類別的主體內容,一個類別只能有一個 constructor,當類別中含有一個以上的建構子方法時,SyntaxError 將會被拋出。在這裡我們把 name 屬性放進 constructor 裡,然後加上 printMyName 方法。

1
2
3
4
5
6
7
8
class Person {
constructor(){
this.name = 'George'
}
printMyName(){
console.log(this.name)
}
}

現在我們已經建立了一個名為 Person 的 Class,已經可以用建構式使用它了。

1
2
3
4
5
6
7
8
9
10
11
class Person {
constructor(){
this.name = 'George'
}
printMyName(){
console.log(this.name)
}
}

const person = new Person()
person.printMyName() //'George'

接著我們來練習 Class 繼承。我們建立一個名為 Human 的類別,然後在原本的 Person 後面用extends關鍵字,extends 是在類別宣告或是類別敘述中建立子類別的方法。接上繼承的父類別名稱 Human,最後在最下方呼叫 person 的 printGender 方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Human {
constructor(){
this.gender = 'Male'
}
printGender(){
console.log(this.gender)
}
}

class Person extends Human {
constructor(){
this.name = 'George'
}
printMyName(){
console.log(this.name)
}
}
const person = new Person()
person.printMyName()
person.printGender() // error

這時系統會拋出 error,這是因為當我們繼承父類別時,在子類別中若有 constructor,要使用 this 前,必須先呼叫super()函式。簡而言之,super是用來提供一個類別呼叫其父類別的函數。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Human {
constructor(){
this.gender = 'Male'
}
printGender(){
console.log(this.gender)
}
}

class Person extends Human {
constructor(){
super() //加上 super() 呼叫父類別建構子
this.name = 'George'
}
printMyName(){
console.log(this.name)
}
}
const person = new Person()
person.printMyName() //'George'
person.printGender() //'Male'

用 extends 擴充傳統函式

你也可以擴充(extends)傳統的函式基礎”類別”。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function Animal (name) {
this.name = name;
}

Animal.prototype.speak = function () {
console.log(this.name + ' makes a noise.');
}

class Dog extends Animal {
speak() {
console.log(this.name + ' barks.');
}
}

var d = new Dog('Mitzie');
d.speak(); // Mitzie barks.

參考連結:
React 16 - The Complete Guide
MDN - Classes
ECMAScript 6 入门 - Class 的基本语法
ECMAScript 6 入门 - Class 的继承
深入理解 JavaScript 中的 class
你所不知道的JS:ES6與未來發展

Share