Node.js 中的原型继承
我正在寻找一种适合我自己的编程风格的在 Node.js 中进行原型继承的方法。对我来说最重要的是使用变量而不是“污染”全局名称空间(如果您不喜欢这个想法,请跳过这个)。我发现了至少六条关于该主题的描述(谷歌有超过 270000 个关于该主题的条目)。
这是我发现的最有希望的变体,但我有一些错误:
> 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)
一旦我发现它是如何工作的,我希望我可以做更复杂的事情,例如:
var B = function() {
this.value = 2;
print();
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试 util.inherits
Try util.inherits
您需要执行以下操作:
然后此示例将按您的预期工作。
You need to do:
And then this example will work as you expect.