Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 373
p1100i Avatar asked Feb 21 '13 23:02

p1100i


1 Answers

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.

like image 200
Pascal Belloncle Avatar answered Oct 22 '22 13:10

Pascal Belloncle