Skip to content

util.inherits does not establish prototype chain #4179

@silkentrance

Description

@silkentrance

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 

Metadata

Metadata

Assignees

No one assigned

    Labels

    docIssues and PRs related to the documentations.utilIssues and PRs related to the built-in util module.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions