I am trying to implement a base class method, that have the same logic for all child classes, but would use some of their variables, that are specific to them.
function A() {}
A.prototype.foo = 'bar';
A.prototype.getFoo = function () {
console.log('Called class: ' + this.constructor.name);
return this.foo;
};
function B() {}
B.prototype.foo = 'qaz';
require('util').inherits(B, A);
console.log(B.prototype.getFoo());
The last line prints bar
, but getFoo() also prints Called class: B
. So I'm wondering, since I can access the child's constructor, is there a way to access child's prototype through it?
require('util').inherits
resets B.prototype
to a new object that inherits A
.
Any properties you set on the old prototype are lost.
If you set B.prototype.foo
after calling inherits()
, it will work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With