Read other articles on Node.js here.
In this article we will have a look at inheritance of objects in Node.js. We will learn how to use a utility module to do inheritance in Node.js. However keep in mind that you can write plain JavaScript to do inheritance in Node as well. You can use Object.create() to inherit an object from another in Node.js also.
First you need to import the "util" module into your application as in the following:
var util = require('util');
After importing the 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 a function to the object using a prototype as in the following:
Student.prototype.Display= function(){
console.log(this.name + " is " + this.age + " years old");
};
Next we will create an ArtsStudent object that will inherit from the Student object.
function ArtsStudent()
{
ArtsStudent.super_.call(this);
this.subject = "music";
};
util.inherits(ArtsStudent,Student);
In the second line of code the ArtsStudent object is very important.
ArtsStudent.super_.call(this);
If you don’t call the constructor of the parent object as shown in the code above snippet then attempts to access properties of the parent object will return undefined.
In the last line ArtStudent inherits Student using the util.inherits() function as in the following:
util.inherits(ArtsStudent, Student);
Next you can create an instance of ArtsStudent and call a function of the parent object as below:
var a = new ArtsStudent();
a.Display();
Inheritance can be chained in any order. If you want, you can inherit an object from ArtsStudent as well. An 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 the above example the ScienceStudent object inherits both Student and ArtsStudent objects. In this way you can work with inheritance in Node.js using the util module. I hope you find this article useful. Thanks for reading.