In this post we'll take a glance on inheritance of objects in Node.js. we'll learn to use utility module to achieve inheritance in Node.js. but confine mind that you simply will write plain JavaScript to attain inheritance in Node also.

You'll use Object.create() to inherit one object to a different in Node.js also.

In this post we'll learn to use util module to achieve inheritance in Node.js. First, you should to import util module in your application.
var util= require(‘util’);

After importing util module, allow us to say you have got an object as below,
function Student()

 this.name = "G Block";
 this.age = 40;
};


Just for demonstration allow us to add function in object using prototype,
Student.prototype.Display= function(){
 console.log(this.name + " is " + this.age + " years old");
 };


Next we tend to we progressing to make ArtsStudent object which is able to inherit Student object.
function ArtsStudent()
{
 ArtsStudent.super_.call(this);
 this.subject = "music";
 }; 
util.inherits(ArtsStudent,Student);


Second line of code in ArtsStudent object is very important,
ArtStudent.super_.call(this);

If you don’t call constructor of parent object as shown in above code snippet then on making an attempt to access properties of parent object will come undefined. In last line ArtStudent inherits Student using util.inherits() function ,

util.iherits(ArtsStudent,Student);

Next you can create instance of ArtsStudent and call function of parent object as below,
var a = new ArtsStudent();
a.Display();


Inheritance will be chained to any order. If you want you can inherit object from ArtsStudent as well. Inherited object will contain properties from both ArtsStudent and Student objects. So let us consider one more example,
function ScienceStudent()
{
 ScienceStudent.super_.call(this);
 this.lab = "Physics";
}
util.inherits(ScienceStudent,ArtsStudent);
var b = new ScienceStudent();
b.Display();

On this example ScienceStudent object inherits both Student and ArtsStudent objects. With this example, you can work with inheritance in Node.js using util module. I hope it works for you!

HostForLIFE.eu Node.js Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.