This is an example to demonstrate polymorphism example, at which if I remove following lines:
Employee.prototype= new Person();
Employee.prototype.constructor=Employee;
there is still no effect on the program and it gets the similar results. If so, how does this example demonstrates polymorphism? Commenting those lines, I see there are 2 functions which when call return results based on their own getInfo functions; so, where is the magic?
HTML:
<script type="text/javascript">
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);
</script>
Result
Reference