Accessing parent prototype functions from Child
As a Senior Principal Engineer at CVSHealth, I specialize in building and optimizing cvs.com to deliver a superior guest experience. Using the latest web technologies, my team and I work diligently to create a user-friendly and intuitive platform that exceeds expectations.
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



