พหุสัณฐาน
ความหลากหลาย เป็นหนึ่งในหลักการของ Object Oriented Programming (OOP) ช่วยในการออกแบบออบเจ็กต์ในลักษณะที่พวกเขาสามารถแบ่งปันหรือแทนที่พฤติกรรมใดๆ กับออบเจ็กต์ที่ระบุเฉพาะ ความหลากหลาย ใช้ประโยชน์จาก มรดก เพื่อให้สิ่งนี้เกิดขึ้น
ในตัวอย่างต่อไปนี้ วัตถุลูก เช่น 'คริกเก็ต ' และ 'เทนนิส ' ได้แทนที่ 'เลือก ' เมธอดที่เรียกจากอ็อบเจกต์หลัก 'เกม ' และส่งคืนสตริงใหม่ตามลำดับตามที่แสดงในเอาต์พุต ในขณะที่เด็กคนอื่นคัดค้าน 'ฟุตบอล' แทนที่จะแทนที่ เลือก เมธอด, แชร์ (สืบทอด) วิธีการและแสดงสตริงหลักตามที่แสดงในเอาต์พุต
ตัวอย่าง
<html>
<body>
<script>
var game = function () {}
game.prototype.select = function()
{
return " i love games and sports"
}
var cricket = function() {}
cricket.prototype = Object.create(game.prototype);
cricket.prototype.select = function() // overridden the select method to display { new string.
return "i love cricket"
}
var tennis = function() {}
tennis.prototype = Object.create(game.prototype); // overridden the select method to display new
tennis.prototype.select = function() string
{
return "i love tennis"
}
var football = function() {}
football.prototype = Object.create(game.prototype); // shared parent property
var games = [new game(), new cricket(), new tennis(), new football()];
games.forEach(function(game){
document.write(game.select());
document.write("</br>");
});
</script>
</body>
</html> ผลลัพธ์
i love games and sports i love cricket i love tennis i love games and sports