Saturday, 23 September 2017

Calling The Super Function In JavaScript



With prototypal inheritance in JavaScript how would you call the super version of a function. Consider Dept that inherits from College as below:


Now you wanted to call displayName() on oDept and you could do that as below:


All of this is simple and cool, but what if you wanted to call the displayName() of College as well from the displayName() in Dept? Something as below:


Notice line-27 where there is an attempt to call the super (College) version of the displayName(). This is however a futile exercise here, as the super is undefined and not recognized. We need to find a way to accomplish this though. Take a look at the solution below:


The trick lies in line-35. Notice that we store the reference to the prototype of Dept in the property uber. You may want to call it super or anything else. Finally it allows us to call the super version of displayName at line number 27.

None of this was possible if we didn't ensure that we had line-34 in place though. Read here if you are wondering why!


No comments:

Post a Comment

The HTML Attributes Never Change!

First things first! What is an HTML attribute? The html attributes provide additional information about or to the element . For instan...