util.inherits() Method in Node.js
0 196
Introduction
The util.inherits()
method in Node.js is part of the Utility Module and is used to establish classical inheritance between constructor functions. It links the prototype of one constructor function to another, allowing objects created from the child constructor to inherit methods from the parent.
Syntax
util.inherits(childConstructor, parentConstructor)
This function connects the prototype chain of childConstructor
to parentConstructor
, allowing inheritance of prototype methods.
Parameters
- childConstructor: The constructor function that will inherit from the parent.
- parentConstructor: The constructor function whose prototype methods will be inherited.
Important Note
util.inherits()
only links prototype methods, not properties defined inside the parent constructor using this
. For full inheritance of properties and methods, consider using ES6 classes.
Example
const util = require('util');
// Parent constructor
function Person() {
this.type = 'Human';
}
Person.prototype.sayHello = function() {
console.log('Hello from Person');
};
// Child constructor
function Student() {
this.level = 'Graduate';
}
// Establish inheritance
util.inherits(Student, Person);
// Test
const stu = new Student();
stu.sayHello(); // Inherited from Person
console.log(stu.level);
Output
Hello from Person
Graduate
Use Cases
- Useful for creating inheritance structures in older Node.js codebases.
- Helps share common behaviors across constructor-based objects.
- Good when not using ES6
class
syntax but still need inheritance.
Conclusion
The util.inherits()
method offers a way to implement prototype-based inheritance in Node.js using traditional constructor functions. While modern JavaScript uses class
and extends
, this method remains useful in legacy code and simpler prototypes.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments