Accessing parent prototype functions from Child

Consider the following code:

function Parent() {}

Parent.prototype.display = function() {

function Child() {}

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

Child.prototype.display = function() {

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);

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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s