Adarsh Konchady
Adarsh Konchady's Blog

Follow

Adarsh Konchady's Blog

Follow

Accessing parent prototype functions from Child

Adarsh Konchady's photo
Adarsh Konchady
·Jan 12, 2016·

1 min read

Consider the following code:

function Parent() {}

Parent.prototype.display = function() {
  console.log('Parent');
}

function Child() {}

Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

Child.prototype.display = function() {
  console.log('Child');
}

var c = new Child();

c.display(); // 'Child'

In the above code, the final line will print 'Child' because c is an object of 'Child'.

Now, if you observed, we did create a link between Child and Parent using 'Object.create'. What if we need the last line to invoke 'Parent display' followed by 'Child display'?

We need to modify the 'Child' display function to accomplish this.

Child.prototype.display = function() {
  var parent = Object.getPrototypeOf(Child.prototype);
  parent.display();
  console.log('Child');
}

We are now getting the 'Parent' prototype reference by using 'Object.getPrototypeOf' on 'Child.prototype'.

Hence the following code will give the desired result:

c.display(); //Parent Child
 
Share this