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 开发者_JS百科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();
}
Try util.inherits
You need to do:
b = new B();
And then this example will work as you expect.
精彩评论