Gilbert
Gilbert

Reputation: 921

How to access class variables in the constructor? (node.js OOP)

Is there some way to access a class variable in the constructor?

var Parent = function() {
  console.log(Parent.name);
};
Parent.name = 'parent';

var Child = function() {
  Parent.apply(this, arguments);
}
require('util').inherits(Child, Parent);
Child.name = 'child';

i.e Parent's constructor should log "parent" and child's Constructor should log "child" based one some class variable in each class.

The above code doesn't work as I expect.

Upvotes: 2

Views: 1370

Answers (1)

generalhenry
generalhenry

Reputation: 17319

Here it is in vanilla js:

var Parent = function() {
  console.log(this.name);
};
Parent.prototype.name = 'parent';

var Child = function() {
  Parent.apply(this, arguments);
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;
Child.prototype.name = 'child';

var parent = new Parent();
var child = new Child();

utils.inherits just simplifies the

Child.prototype = new Parent();
Child.prototype.constructor = Child;

into

util.inherits(Child, Parent);

Upvotes: 1

Related Questions