turbo
turbo

Reputation: 589

util inherits in node

Trying to understand inheritance support provided by node's util package.

var util = require('util');

//=========================================
function Foo(temp){
    this.y = temp;
}

Foo.prototype.yo = function(){
    console.log("Yo "+this.y);
}

//=========================================

function Bar(){}
util.inherits(Bar,Foo);

var b = new Bar(20);
//b.y = 10; 
b.yo();

Here b.yo() prints "Yo undefined". It calls the Foo's yo() so i suppose inheritance is working. But it doesnt print the y value. If b.y = 10 line uncommented then it prints the 10 value. Trying to understand why this happened.

Upvotes: 0

Views: 192

Answers (1)

zerkms
zerkms

Reputation: 254916

Bar's constructor is empty.

When you inherit something it copies the prototype attributes, but you must implement a constructor properly by yourself.

So you technically can do this:

function Bar(temp) {
    Foo.call(this, temp);
}

Upvotes: 4

Related Questions