-1

I have the following Meta-Code

var Parent = function(){}
Parent.prototype.doSomething = function(){
  console.log("As a parent I did like a parent");
}

var Child = function(){}
Child.prototype = new Parent();
Child.prototype.doSomething = function(){
  console.log("As a child I did like a child");
  //This is where I am not sure what to put
}

What I would like it 2 lines

As a child I did like a child
As a parent I did like a parent

Of course the first one is simple but I am not sure how/if I can call a parent function once it has been overridden.

Jackie
  • 21,969
  • 32
  • 147
  • 289

2 Answers2

1

One way to do this is calling Parent.prototype.method.call(this, arg1, arg2, ...). You can read more about super calls in HERE.

var Child = function(){}
Child.prototype = new Parent();

Child.prototype.doSomething = function(){
  console.log("As a child I did like a child");
  Parent.prototype.doSomething.call(this); //with this line
}
Cem Özer
  • 1,263
  • 11
  • 19
1

You could save the base method by doing something like this:

var Parent = function () {}
Parent.prototype.doSomething = function () {
    alert("As a parent I did like a parent");
}

var Child = function () {}
Child.prototype = new Parent();
Child.prototype.doSomething = (function () {
    // since this is an IIFE - Child.prototype.doSomething will refer to the base
    // implementation. We haven't assigned this new one yet!
    var parent_doSomething = Child.prototype.doSomething;   
    return function () {
        alert("As a child I did like a child");
        parent_doSomething();
    }
})();

var c = new Child();
c.doSomething();

Which has the advantage of not having to worry about who the parent was. Although you should probably check that the parent has a doSomething method.

Matt Burland
  • 44,552
  • 18
  • 99
  • 171