0

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();
}

2 Answers 2

2

Try util.inherits

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the hint. I have seen a discussion about deprecating util.inherits thats why I prefer the prototype.__proto__ variant I used in the example.
1

You need to do:

b = new B();

And then this example will work as you expect.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.