Polymorphism
Polymorphism means we can treat objects of different types as objects of one common, more general type.
In JavaScript, a subclass can override an inherited method, and that is what gives us polymorphism.
class CourseAssistant {
getBaseSalary() {
return 500.0; // dollars
}
getHourlyPayRate() {
return 15.0; // dollars
}
}
class ExperiencedCourseAssistant extends CourseAssistant {
/* overrides */
getHourlyPayRate() {
return 1.1 * super.getHourlyPayRate();
}
}
function calcPayment(courseAssistant, hoursWorked) {
let wages =
courseAssistant.getBaseSalary() +
hoursWorked * courseAssistant.getHourlyPayRate(); /* dynamic dispatch */
console.log(wages);
}
const tom = new CourseAssistant();
const mona = new ExperiencedCourseAssistant();
calcPayment(tom, 10); // 650
calcPayment(mona, 10); // 665
In the code above, the call to getHourlyPayRate() is dispatched based on the actual type of the courseAssistant argument. JavaScript decides at runtime whether to call the overridden getHourlyPayRate() or the one in the parent class. That is dynamic dispatch, and it is what makes the behavior polymorphic.
Note: JavaScript does not support method overloading because a method can accept fewer or more arguments than its declared parameters.