镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
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 <thechargingvolcano@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent c9786bb commit 8057315

2 files changed

Lines changed: 35 additions & 8 deletions

File tree

‎lib/util.js‎

Lines changed: 1 addition & 8 deletions
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‎

Lines changed: 34 additions & 0 deletions
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)