Search code examples
javascriptnode.jsprototypeprototypal-inheritance

When should someone use util.inherits() over prototypes in node.js for inheritance?


util.inherits(): Inherits methods from one function into another

Prototypes: Also offers inheritance.

So when should I use .inherits() and when should I change the prototype chain? Thanks.


Solution

  • So when should I use .inherits() and when should I change the prototype chain?

    util.inherits() uses the prototype so that assumption on your part is wrong.

    It creates a new prototype object and copies over the properties from the previous prototype to make you a new prototype object that you can then add your own properties to.

    What the node.js doc for util.inherits() recommends is that you use the ES6 class and extends syntax instead and Object.create() is also available. util.inherits() is an old style way of doing things - it uses the prototype and it works, but is has been superceded by standard syntax. I am not aware of any reason to continue to use it.