Node.js 中的原型继承

发布于 2024-11-03 08:18:34 字数 1107 浏览 0 评论 0原文

我正在寻找一种适合我自己的编程风格的在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟雨凡馨 2024-11-10 08:18:34

您需要执行以下操作:

b = new B();

然后此示例将按您的预期工作。

You need to do:

b = new B();

And then this example will work as you expect.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文