Andy的前後端技術筆記、生活紀錄
Javascript建構子函式繼承及ES6的class方式的繼承
發佈於: 2024-04-14 更新於: 2024-04-21 分類於: frontend > frontend_interview

如何以建構函式的方式達到繼承

繼承在OOP物件導向的語言中很常見,而在Javascript中並不是真正的物件導向的語言,所以在Javascript中繼承的方式就不一樣,這裡用建構子函式的方式來實作繼承。

建構子函式的繼承

在Javascript中,我們可以用建構子函式的方式達到繼承,如果現在有一個Vehicle的父建構函式(父類別)而後我要建立一個Car子建構函式(子類別),而若是我希望繼承Vehicle裡面的property,可以如下操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

//建立父建構函式及其prototype
function Vehicle(type, length, width) {
this.type = type;
this.length = length;
this.width = width;
}

// 建立一個method
Vehicle.prototype.start = function() {
console.log("start");
}



//繼承Vehicle的prototype
function Car(type, length, width, color) {
Vehicle.call(this, type, length, width);
//把Vehicle的prototype的property繼承到Car的prototype constructor中
this.color = color;
}

//建立一個與Vehicle相同的prototype給Car.prototype
Car.prototype = Object.create(Vehicle.prototype);

// 但因為其constructor是希望使用Car自己的也就是this.color這些自訂的property,所以我們要把Car.prototype.constructor指向Car
Car.prototype.constructor = Car;


//建立一個Car的instance
const myCar = new Car("BMW", 150, 100, "red");

//使用繼承vehicle的method
myCar.start();

console.log(myCar.color);
// red

// 而若是要在Car新增method,可以這沒做
Car.prototype.stop = function() {
console.log("stop");
}

myCar.stop();
// stop

改以ES6的class方式達到繼承

這樣就清晰易懂的多了,但是Class只是Javascript的語法糖,讓使用者可以更容易實現繼承,但其底層的原理還是以prototype chain的方式達到繼承。範例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Vehicle {
constructor(type, length, width) {
this.type = type;
this.length = length;
this.width = width;
}

start() {
console.log("start");
}
}

class Car extends Vehicle {
constructor(type, length, width, color) {
super(type, length, width); // 把vehicle的constructor繼承過來並且把this指向Car
this.color = color;
}

stop() {
console.log("stop");
}
}

const myCar = new Car("BMW", 150, 100, "red");

myCar.start();
console.log(myCar.color); // red
myCar.stop();

--- 到底拉 The End ---