-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.

1
  • Here is an example for you: jsfiddle.net/zu097ep4 Commented Sep 25, 2014 at 14:21

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.