JavaScript 中的多型性

Mehvish Ashiq 2023年10月12日

什麼是 JavaScript 中的多型性

`Poly` 一詞的意思是`許多``多個``morph` 的意思是`形式`。因此，`多型性`意味著`多種形式``多種形式`

1. 靜態多型
2. 動態多型

在 JavaScript 中為什麼使用多型性

1. 我們可以重用已經編寫和測試過的程式碼。
2. 由於使用了多型，程式碼很容易除錯。
3. 節省時間，提高工作質量。

JavaScript 中的多型性如何工作

JavaScript 中的靜態多型是如何工作的

``````class calculator {
constructor() {}
sum(num1, num2, num3) {
if (num3 != undefined) {
console.log('Sum is called with three parameters');
return num1 + num2 + num3;
} else {
console.log('Sum is called with two parameters');
return num1 + num2;
}
}
}

const c = new calculator();
console.log(c.sum(2, 3));
console.log(c.sum(2, 3, 4));
``````

``````"Sum is called with two parameters"
5
"Sum is called with three parameters"
9
``````

``````class calculator {
constructor() {}
sum(num1, num2, num3, num4) {
if (num4 != undefined) {
console.log('Sum is called with four parameters');
return num1 + num2 + num3 + num4;
} else if (num3 != undefined) {
console.log('Sum is called with three parameters');
return num1 + num2 + num3;
} else {
console.log('Sum is called with two parameters');
return num1 + num2;
}
}
}

const c = new calculator();
console.log(c.sum(2, 3));
console.log(c.sum(2, 3, 4));
console.log(c.sum(2, 3, 4, 5));
``````

``````"Sum is called with two parameters"
5
"Sum is called with three parameters"
9
"Sum is called with four parameters"
14
``````

在 JavaScript 中動態多型性如何工作

`形狀`類：

``````class Shape {
calculateArea() {
console.log('shape.calculateArea is called.');
return 0;
}
}
``````

`矩形`類：

``````class Rectangle extends Shape {
constructor(length, width) {
super();
this.length = length;
this.width = width;
}
calculateArea() {
console.log('rectangle.calculateArea is called.');
return this.length * this.width;
}
}
``````

`圈`類：

``````class Circle extends Shape {
super();
}
calculateArea() {
console.log('circle.calculateArea is called.');
return Math.PI * this.radius ** 2;
}
}
``````

``````s = new Rectangle(3, 4);
console.log(s.calculateArea());
s = new Circle(2);
console.log(s.calculateArea());
``````

``````"rectangle.calculateArea is called."
12
"circle.calculateArea is called."
12.566370614359172
``````

`s` 在此程式碼中包含 `Rectangle` 類的引用 `s = new Rectangle(3,4);` 但它在程式碼 `s= new Circle(2);` 中包含 `Circle` 類的引用。

``````"rectangle.calculateArea is called."
12
"shape.calculateArea is called."
0
``````

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.