How to call a parent method from child class in javascript?

I’ve spent the last couple of hours trying to find a solution to my problem but it seems to be hopeless.

Basically I need to know how to call a parent method from a child class.
All the stuff that I’ve tried so far ends up in either not working or over-writing the parent method.

I am using the following code to set up OOP in javascript:

// SET UP OOP
// surrogate constructor (empty function)
function surrogateCtor() {}

function extend(base, sub) {
    // copy the prototype from the base to setup inheritance
    surrogateCtor.prototype = base.prototype;
    sub.prototype = new surrogateCtor();
    sub.prototype.constructor = sub;
}

// parent class
function ParentObject(name) {
    this.name = name;
}
// parent's methods
ParentObject.prototype = {
    myMethod: function(arg) {
        this.name = arg;
    }
}

// child
function ChildObject(name) {
    // call the parent's constructor
    ParentObject.call(this, name);
    this.myMethod = function(arg) {
        // HOW DO I CALL THE PARENT METHOD HERE?
        // do stuff
    }
}

// setup the prototype chain
extend(ParentObject, ChildObject);

I need to call the parent’s method first and then add some more stuff to it in the child class.

In most OOP languages that would be as simple as calling parent.myMethod()
But I really cant grasp how its done in javascript.

Any help is much appreciated, thank you!

9 Answers
9

Leave a Comment