I have read some possible article I could found on the internet on polymorphism. But I think I could not quite grasp the meaning of it and its importance. Most of the articles don't say why it is important and how I can achieve polymorphic behavior in OOP (of course in JavaScript).
I can not provide any code example because I haven't got the idea how to implement it, so my questions are below:
- What is it?
- Why we need it ?
- How it works?
- How can I achieve this polymorphic behavior in javascript?
I have got this example. But it is easily understandable what will be outcome of this code. It doesn't give any clear idea about polymorphism itself.
function Person(age, weight) {
this.age = age;
this.weight = weight;
this.getInfo = function() {
return I am + this.age + years old +
and weighs + this.weight + kilo.;
}
}
function Employee(age, weight, salary) {
this.salary = salary;
this.age = age;
this.weight = weight;
this.getInfo = function() {
return I am + this.age + years old +
and weighs + this.weight + kilo +
and earns + this.salary + dollar.;
}
}
Employee.prototype = new Person();
Employee.prototype.constructor = Employee;
// The argument, 'obj', can be of any kind
// which method, getInfo(), to be executed depend on the object
// that 'obj' refer to.
function showInfo(obj) {
document.write(obj.getInfo() + <br>);
}
var person = new Person(50,90);
var employee = new Employee(43,80,50000);
showInfo(person);
showInfo(employee);