简体   繁体   中英

Inheritance in JavaScript: Calling parent's method

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM