Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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?

Problem courtesy of: p1100i

Solution

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.

Solution courtesy of: Pascal Belloncle

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×