Javascript

Accessing parent prototype functions from Child

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
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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