2

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.

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

utils.inherits does more than described (no instance of a subclass).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.