Polymorphism ใน JavaScript
Polymorphism (หลายรูป) เป็นหลักการ OOP ให้ Object แบบต่างๆ ตอบสนองต่อ Message เดียวกันได้ต่างกัน (Override) หรือใช้ร่วมกันได้ (Inheritance)
Prototype-based Polymorphism
<script>
// Parent "Class"
var Game = function() {};
Game.prototype.select = function() {
return 'I love games and sports';
};
// Child: Cricket (Override)
var Cricket = function() {};
Cricket.prototype = Object.create(Game.prototype);
Cricket.prototype.select = function() {
return 'I love cricket';
};
// Child: Tennis (Override)
var Tennis = function() {};
Tennis.prototype = Object.create(Game.prototype);
Tennis.prototype.select = function() {
return 'I love tennis';
};
// Child: Football (Inherit - No Override)
var Football = function() {};
Football.prototype = Object.create(Game.prototype);
// Polymorphism ในการทำงาน
var games = [new Game(), new Cricket(), new Tennis(), new Football()];
games.forEach(function(game) {
document.write(game.select() + '<br>');
});
</script>
ผลลัพธ์
I love games and sports I love cricket I love tennis I love games and sports
ES6 Class Syntax (Modern)
class Game {
select() { return 'I love games and sports'; }
}
class Cricket extends Game {
select() { return 'I love cricket'; }
}
class Tennis extends Game {
select() { return 'I love tennis'; }
}
class Football extends Game {} // Inherit
const games = [new Game(), new Cricket(), new Tennis(), new Football()];
games.forEach(g => console.log(g.select()));
ประเภทของ Polymorphism
| Type | คำอธิบาย | JavaScript |
|---|---|---|
| Subtype (Inclusion) | Child ใช้แทน Parent ได้ | Prototype/Class Inheritance |
| Ad-hoc (Overloading) | ฟังก์ชันชื่อเดียว Parameter ต่างกัน | ไม่รองรับโดยตรง (ใช้ Default/Rest Params) |
| Parametric (Generics) | ทำงานกับ Type ใดๆ | Duck Typing / Generics (TypeScript) |