moin moin
moin moin

Reputation: 2453

prototypal inheritance in node.js

I am looking for a way on how to do prototypal inheritance in node.js that fits my own programming style. Most important for me is to use variables instead of "polluting" the global namespace (if you do not like that idea please skip this one). I found at least half a dozen descriptions on the topic (google has over 270000 entries on that one).

Here is what I found the most promising variant but I have got something wrong:

> var A = function() {
... this.value = 1;
... };
> A.prototype.print = function() {
... console.log(this.value);
... }
[Function]
> var a = new A();
> a.print();
1
> var B = function() {
... this.value = 2;
... };
> B.prototype.__proto__ = A.prototype;
> b = B();
> b.print()
TypeError: Cannot call method 'print' of undefined
    at [object Context]:1:3
    at Interface.<anonymous> (repl.js:150:22)
    at Interface.emit (events.js:42:17)
    at Interface._onLine (readline.js:132:10)
    at Interface._line (readline.js:387:8)
    at Interface._ttyWrite (readline.js:564:14)
    at ReadStream.<anonymous> (readline.js:52:12)
    at ReadStream.emit (events.js:59:20)
    at ReadStream._emitKey (tty_posix.js:286:10)
    at ReadStream.onData (tty_posix.js:49:12)

Once I found out how this works I hope I can do even more complicated stuff like:

var B = function() {
  this.value = 2;
  print();
}

Upvotes: 0

Views: 682

Answers (2)

Matt Ranney
Matt Ranney

Reputation: 1638

You need to do:

b = new B();

And then this example will work as you expect.

Upvotes: 1

Lee Treveil
Lee Treveil

Reputation: 6845

Try util.inherits

Upvotes: 2

Related Questions