Read other posts on Node.js here
In this post we will take a look on inheritance of objects in Node.js. We will learn to use utility module to achieve inheritance in Node.js. However keep in mind that you can write plain JavaScript to achieve inheritance in Node as well. You can use Object.create() to inherit one object to another in Node.js also.
In this post we will learn to use util module to achieve inheritance in Node.js. Very first you need to import util module in your application
After importing util module, let us say you have an object as below,
function Student() { this.name = "G Block"; this.age = 40; };
Just for demonstration let us add function in object using prototype,
Student.prototype.Display= function(){ console.log(this.name + " is " + this.age + " years old"); };
Next we are going to create ArtsStudent object which will 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,
If you don’t call constructor of parent object as shown in above code snippet then on trying to access properties of parent object will return undefined.
In last line ArtStudent inherits Student using util.inherits() function ,
Next you can create instance of ArtsStudent and call function of parent object as below,
var a = new ArtsStudent(); a.Display();
Inheritance can 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();
In above example ScienceStudent object inherits both Student and ArtsStudent objects. In this way you can work with inheritance in Node.js using util module. I hope you find this post useful. Thanks for reading.
Leave a Reply