简体   繁体   中英

Accessing child class prototype from parent class

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM