Skip to content

Commit

Permalink
stream: fix Writable subclass instanceof checks
Browse files Browse the repository at this point in the history
2a4b068 introduced a regression in where checking
`instanceof` would fail for `Writable` subclasses inside the
subclass constructor, i.e. before `Writable()` was called.

Also, calling `null instanceof Writable` or
`undefined instanceof Writable` would fail due to accessing the
`_writableState` property of the target object.

This fixes these problems.

Ref: nodejs#8834 (comment)
  • Loading branch information
addaleax committed Oct 13, 2016
1 parent 804d57d commit 7fe8672
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/_stream_writable.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,12 @@ if (typeof Symbol === 'function' && Symbol.hasInstance) {
realHasInstance = Function.prototype[Symbol.hasInstance];
Object.defineProperty(Writable, Symbol.hasInstance, {
value: function(object) {
if (realHasInstance.call(this, object))
return true;

// Trying to move the `realHasInstance` from the Writable constructor
// to here will break the Node.js LazyTransform implementation.
return object._writableState instanceof WritableState;
return object && object._writableState instanceof WritableState;
}
});
} else {
Expand Down
16 changes: 16 additions & 0 deletions test/parallel/test-stream-inheritance.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,19 @@ assert.ok(!(readable instanceof Transform));
assert.ok(!(writable instanceof Transform));
assert.ok(!(duplex instanceof Transform));
assert.ok(transform instanceof Transform);

assert.ok(!(null instanceof Writable));
assert.ok(!(undefined instanceof Writable));

// Simple inheritance check for `Writable` works fine in a subclass constructor.
function CustomWritable() {
assert.ok(this instanceof Writable, 'inhertis from Writable');
assert.ok(this instanceof CustomWritable, 'inherits from CustomWritable');
}

Object.setPrototypeOf(CustomWritable, Writable);
Object.setPrototypeOf(CustomWritable.prototype, Writable.prototype);

new CustomWritable();

assert.throws(CustomWritable, /AssertionError: inhertis from Writable/);

0 comments on commit 7fe8672

Please sign in to comment.