我正在尋找如何在node.js中做適合我自己的編程風格的原型繼承的方法。對我來說最重要的是使用變量而不是「污染」全局命名空間(如果你不喜歡這個想法,請跳過這一點)。我發現至少有六個關於這個主題的描述(谷歌在那一個上有超過270000個條目)。node.js中的原型繼承
這是我發現的最有前途的變量,但我有一些錯誤:
> 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();
}
太棒了!非常感謝,你救了我的一天 – mark 2011-04-25 10:03:28