p1100i p1100i - 5 months ago 15
Node.js Question

util.inherits - how to call method of super on instance?

I'm playing with

util.inherits
method from node.js and can't seem to get the desired behavior.

var util = require("util");

function A() {
this.name = 'old';
}

A.prototype.log = function(){
console.log('my old name is: '+ this.name);
};

function B(){
A.call(this);
this.name = 'new';
}

util.inherits(B, A);

B.prototype.log = function(){
B.super_.prototype.log();
console.log('my new name is: ' + this.name);
}

var b = new B();
b.log();


The result is:

my old name is: undefined
my new name is: new


However what I would like is:

my old name is: new
my new name is: new


What am I missing?

Answer

Here's how to achieve what you are looking for:

B.prototype.log = function () {
  B.super_.prototype.log.apply(this);

  console.log('my new name is: ' + this.name);
};

This ensures the this context is the instance of B instead of being B.super_.prototype I suppose.

Comments