Skip to content

Commit 8057315

Browse files
targosrvagg
authored andcommitted
util: make inherits work with classes
The current implementation overwrites the prototype of the target constructor. It is not allowed with ES2015 classes because the prototype property is read only. Use Object.setPrototypeOf instead. Fixes: #3452 PR-URL: #3455 Reviewed-By: Sakthipriyan Vairamani <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent c9786bb commit 8057315

File tree

2 files changed

+35
-8
lines changed

2 files changed

+35
-8
lines changed

lib/util.js

+1-8
Original file line numberDiff line numberDiff line change
@@ -761,14 +761,7 @@ exports.inherits = function(ctor, superCtor) {
761761
'have a prototype.');
762762

763763
ctor.super_ = superCtor;
764-
ctor.prototype = Object.create(superCtor.prototype, {
765-
constructor: {
766-
value: ctor,
767-
enumerable: false,
768-
writable: true,
769-
configurable: true
770-
}
771-
});
764+
Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
772765
};
773766

774767
exports._extend = function(origin, add) {

test/parallel/test-util-inherits.js

+34
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,40 @@ const c = new C();
4040
assert.strictEqual(c.getValue(), 'abc');
4141
assert.strictEqual(c.constructor, C);
4242

43+
// inherits can be called after setting prototype properties
44+
function D() {
45+
C.call(this);
46+
this._d = 'd';
47+
}
48+
49+
D.prototype.d = function() { return this._d; };
50+
inherits(D, C);
51+
52+
assert.strictEqual(D.super_, C);
53+
54+
const d = new D();
55+
assert.strictEqual(d.c(), 'c');
56+
assert.strictEqual(d.d(), 'd');
57+
assert.strictEqual(d.constructor, D);
58+
59+
// ES6 classes can inherit from a constructor function
60+
class E {
61+
constructor() {
62+
D.call(this);
63+
this._e = 'e';
64+
}
65+
e() { return this._e; }
66+
}
67+
inherits(E, D);
68+
69+
assert.strictEqual(E.super_, D);
70+
71+
const e = new E();
72+
assert.strictEqual(e.getValue(), 'abc');
73+
assert.strictEqual(e.d(), 'd');
74+
assert.strictEqual(e.e(), 'e');
75+
assert.strictEqual(e.constructor, E);
76+
4377
// should throw with invalid arguments
4478
assert.throws(function() { inherits(A, {}); }, TypeError);
4579
assert.throws(function() { inherits(A, null); }, TypeError);

0 commit comments

Comments
 (0)