Polymorphism in Java Script
Polymorphism
The ability to call the same method on different objects and have each of them respond in their own way is called polymorphism.
Polymorphism is the main pillar of Object Oriented Programming, it refers to the ability of an object to provide different behaviors in different state of objects.
Example
Parent class Human define a function of introduction() in which it contains simple introduction but Student object override it by adding more detailed information for introduction. So now Human() object has its own implementation of introduction and Student() has its own. It will be invoked according to the state of object.
//Define human class
function Human(fullName) {
this.fullName = fullName;
}
// Add a couple of methods to Human.prototype
Human.prototype.speak = function(){
alert("I speak English!");
};
Human.prototype.introduction = function(){
alert("Hi, I am " + this.fullName);
};
//Define Student class
function Student(fullName, school, courses) {
Human.call(this, fullName);
// Initialize our Student properties
this.school = school;
this.courses = courses;
};
Student.prototype = Object.create(Human.prototype); // See note below
// Set the "constructor" property to refer to Student
Student.prototype.constructor = Student;
// override the "introduction" method
Student.prototype.introduction= function(){
alert("Hi, I am " + this.fullName + ". I am a student of " + this.school + ", I study "+ this.courses +".");
};
// Add a "exams" method
Student.prototype.takeExams = function(){
alert("This is my exams time!");
};
var student = new Student("Ahmed","NED University", "Computer Science");
student.introduction(); // "Hi, I am Ahmed. I am a student of NED University, I study Computer Science."
student.speak(); // "I speak English!"
student.takeExams(); // "This is my exams time!"
// Check that instanceof works correctly
alert(student instanceof Human); // true
alert(student instanceof Student); // true
Comments
Post a Comment