I am trying to emulate polymorphism through ES6 Classes, in order to be able to better understand this theory.
Concept is clear (designing objects to share behaviors and to be able to override shared behaviors with specific ones) but I am afraid my code above is not a valid polymorphism example.
Due to my lack of experience, I appreciate if you answer these questions in a comprehensive way:
Employee.prototype = new Person();
line, and it still works. This is why I am afraid I'm not getting this concept.class Person {
constructor (name, age) {
this._name = name;
this._age = age;
}
}
Person.prototype.showInfo = function(){
return "Im " + this._name + ", aged " + this._age;
};
class Employee {
constructor (name, age, sex) {
this._name = name;
this._age = age;
this._sex = sex;
}
}
Employee.prototype = new Person();
Employee.prototype.showInfo = function(){
return "Im " + this._sex + ", named " + this._name + ", aged " + this._age;
};
var myPerson = new Person('Jon', 20);
var myEmployee = new Employee('Doe', 10, 'men');
document.write(myPerson.showInfo() + "<br><br>"); // Im Jon, aged 20
document.write(myEmployee.showInfo() + "<br><br>"); // Im men, named Doe, aged 10
Every JavaScript object has an internal "prototype" property, often called [[prototype]], which points to the object from which it directly inherits.
Every JavaScript function [object] has a property prototype, which is initialized with an [nearly] empty object. When you create a new instance of this function by calling it as a constructor, the [[prototype]] of that new object will point to the constructor's prototype object.
So, when you write this var myPerson = new Person('Jon', 20);
,you have the method showInfo because you have this
Person.prototype.showInfo = function(){
return "Im " + this._name + ", aged " + this._age;
};
With ES6 if you want to see the polymorphism you could do that :
class Person {
constructor (name, age) {
this._name = name;
this._age = age;
}
showInfo () {
return "Im " + this._name + ", aged " + this._age;
}
}
class Employee extends Person {
constructor (name, age, sex) {
super(name,age);
this._sex = sex;
}
showInfo(){
return "Im " + this._sex + ", named " + this._name + ", aged " + this._age;
}
}
var myPerson = new Person('Jon', 20);
var myEmployee = new Employee('Doe', 10, 'men');
document.write(myPerson.showInfo() + "<br><br>"); // Im Jon, aged 20
document.write(myEmployee.showInfo() + "<br><br>"); // Im men, named Doe, aged 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With