util.inherits does not establish prototype chain · Issue #4179 · nodejs/node (original) (raw)

In inherits.js Object.setPrototypeOf is being called with the wrong parameters.

The reason for me assuming that the wrong parameters are being used is

(REPL)

> function MyError() {}
> util.inherits(MyError, Error);
> MyError
{ [Function: MyError]
  super_: 
   { [Function: Error]
     captureStackTrace: [Function: captureStackTrace],
     stackTraceLimit: 10 } }
> Error.isPrototypeOf(MyError);
false

While inheritance sort of works, the prototype chain is actually never established.

> myerr = new MyError()
[Error]
> myerr instanceof MyError
true
> myerr instanceof Error
true

Replacing the existing call to Object.setPrototypeOf() by

Object.setPrototypeOf(ctor, superCtor);

See https://github.com/nodejs/node/blob/master/lib/util.js#L805.

(REPL)

> function MyError() {}
> util.inherits(MyError, Error);
> MyError
[Function: OError]
> Error.isPrototypeOf(MyError);
true

Yet, instanceof will now fail

> myerr = new MyError()
[Error]
> myerr instanceof MyError
true
> myerr instanceof Error
false

When using the new class feature, everything works as expected, though

(REPL)

> class MyError extends Error {}
[Function: MyError]
> Error.isPrototypeOf(MyError)
true
> myerr = new MyError()
[Error]
> myerr instanceof MyError
true
> myerr instanceof Error
true