Reputation: 4771
The way I implement inheritance in JavaScript is shown in the example below. I am trying to call from the child class a method of the parent class. I have seen many examples online, that add the parent method to the prototype, and the use the call or apply function (but my implementation is not doing that). Is there a way to make this type of call?
function classM() //parent class
{
this.myName = function()
{
console.log('parent');
}
}
function classEM ()
{
classM.call(this);
this.myName = function()
{
console.log('child');
//HOW DO I CALL myName() of the parent class?
}
}
classEM.prototype = Object.create(classM.prototype);
classEM.prototype.constructor = classEM;
var rm = new classEM();
rm.myName(); //should print child and then parent
Upvotes: 0
Views: 120
Reputation: 239683
When you do this.myName = ...
in classEM
, you are replacing the old myName
function created by the parent with the one in classEM
. So only one function exists now. Instead, you can add the myName
function in the classM
's prototype and inherit from it.
So the program becomes like this
function classM() {}
// Add myName to the parent
classM.prototype.myName = function() {
console.log('parent');
}
function classEM() {
this.myName = function() {
// Get the parent prototype object and invoke the myName in it.
Object.getPrototypeOf(this).myName();
console.log('child');
}
}
classEM.prototype = Object.create(classM.prototype);
classEM.prototype.constructor = classEM;
var rm = new classEM();
rm.myName();
Output
parent
child
Upvotes: 2