Search code examples
javascriptnode.jsecmascript-6prototype

Why does the util.inherits() method in Node.js uses Object.setPrototypeOf()?


I am new to Node.js, but already quite profound of JavaScript and its prototypal ecosystem. What I have generally heard is that Object.setPrototypeOf(), or assigning a new value to an object's __proto__ property, is bad.

These [[Prototype]] mutations cause performance issues and lead to less optimized code. Now, when I try to get my mind, somehow, around this idea, I see that the util.inherits() method in Node.js uses Object.setPrototypeOf() to set the prototype of the first arg. The source can be found at lib/util.js.

If Object.setPrototypeOf() is really that bad, what's the reason that Node.js uses it for configuring the prototype of a given object?

And, would Object.setPrototypeOf() still be that damaging if I call it at the start of a given script, and be careful never to call it at runtime?


Solution

  • Just like setPrototypeOf is discouraged for the reasons you give, so is util.inherits -- for the same reasons. Quoted from the documentation:

    Usage of util.inherits() is discouraged. Please use the ES6 class and extends keywords to get language level inheritance support. Also note that the two styles are semantically incompatible.

    This also suggests what you should be doing to avoid both setPrototypeOf and util.inherits.

    MDN adds this suggestion:

    if you are concerned about performance, you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using Object.create().