Browse Source

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: https://github.com/nodejs/node/issues/3452
PR-URL: https://github.com/nodejs/node/pull/3455
Reviewed-By: Sakthipriyan Vairamani <thechargingvolcano@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
process-exit-stdio-flushing
Michaël Zasso 9 years ago
parent
commit
29da8cf8d7
  1. 9
      lib/util.js
  2. 34
      test/parallel/test-util-inherits.js

9
lib/util.js

@ -761,14 +761,7 @@ exports.inherits = function(ctor, superCtor) {
'have a prototype.'); 'have a prototype.');
ctor.super_ = superCtor; ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, { Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}; };
exports._extend = function(origin, add) { exports._extend = function(origin, add) {

34
test/parallel/test-util-inherits.js

@ -40,6 +40,40 @@ const c = new C();
assert.strictEqual(c.getValue(), 'abc'); assert.strictEqual(c.getValue(), 'abc');
assert.strictEqual(c.constructor, C); assert.strictEqual(c.constructor, C);
// inherits can be called after setting prototype properties
function D() {
C.call(this);
this._d = 'd';
}
D.prototype.d = function() { return this._d; };
inherits(D, C);
assert.strictEqual(D.super_, C);
const d = new D();
assert.strictEqual(d.c(), 'c');
assert.strictEqual(d.d(), 'd');
assert.strictEqual(d.constructor, D);
// ES6 classes can inherit from a constructor function
class E {
constructor() {
D.call(this);
this._e = 'e';
}
e() { return this._e; }
}
inherits(E, D);
assert.strictEqual(E.super_, D);
const e = new E();
assert.strictEqual(e.getValue(), 'abc');
assert.strictEqual(e.d(), 'd');
assert.strictEqual(e.e(), 'e');
assert.strictEqual(e.constructor, E);
// should throw with invalid arguments // should throw with invalid arguments
assert.throws(function() { inherits(A, {}); }, TypeError); assert.throws(function() { inherits(A, {}); }, TypeError);
assert.throws(function() { inherits(A, null); }, TypeError); assert.throws(function() { inherits(A, null); }, TypeError);

Loading…
Cancel
Save