Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 257
klkvsk Avatar asked Aug 08 '13 15:08

klkvsk


1 Answers

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.

like image 130
SLaks Avatar answered Sep 21 '22 13:09

SLaks