My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
subclassing (inheritance) in Java Script (under the hood)

subclassing (inheritance) in Java Script (under the hood)

prashant's photo
prashant
·Jan 7, 2022·

2 min read

How inheritance works in JS? Actually javascript is prototypal language. So inheritance in javascript is different from other traditional languages like java, c++. In javascript one object is linked to other object to achieve code reusability.

let's look at different kind of approaches to achieve the same.

1) approach-1

suppose we have two kinds of users. one is normal user and other is paid user and paid user has some additional functionality which are not present in normal user. So normal user will not have access to extra functionality. Let's look at solution how we can achieve code reusability in other terms inheritance.

in below snap shot we are creating userFunctions object and adding methods for normal user.

approach_1_1.png

now we will look at the code for the paidUser which has additional functionality. Here we will create a object (i.e. paidUserFunctions) who's proto is linked to userFunctions and will add methods which are extra for paidUser. In paidUserCreator we are using userCreator for code reusability and will set the proto to the paidUserFunctions (using setPrototyprOf). Notice that our paidUserFunctions has already access to all methods of normal user and paid user.

approach1_2_final.png

2) approach-2

In approach-1 we are doing lots of thing like creating object and linking it to other object and then return it . so let's automate this with help of new keyword.

Here we are changing prototype of createPaidUser Function. first we are assigning empty object whose proto is linked to createUser.prototype, and then we are adding additional methods to createPaidUser's prototype.

We are using call method to invoke createUser function because we want to maintain the same "this" reference to add the properties of createUser function.

approach_2.png

3) approach-3

In approach-2 we were using prototype to add the functionality. Now lets simplify further using class.

super will call userCreator function and creates new object there and add properties, also links proto of created object to paidUserCreator's prototype and returns it and returned object will be assigned to "this" label inside paidUserCreator (i.e. constructor), then we will add additional properties to the object stored under this label.

extends will link proto of object returned by userCreator to userCreator's prototype.

approach-3.png

Thanks for reading!!!

Please like and comment if you have any doubts.