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

YemSalat picture YemSalat · Aug 8, 2012 · Viewed 181.7k times · Source

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!

Answer

YemSalat picture YemSalat · Aug 8, 2012

Here's how its done: ParentClass.prototype.myMethod();

Or if you want to call it in the context of the current instance, you can do: ParentClass.prototype.myMethod.call(this)

Same goes for calling a parent method from child class with arguments: ParentClass.prototype.myMethod.call(this, arg1, arg2, ..) * Hint: use apply() instead of call() to pass arguments as an array.