2011-04-25 15 views
0

私自身のプログラミングスタイルに合ったnode.jsのプロトタイプ継承を行う方法を探しています。私にとって最も重要なのは、グローバル名前空間を "汚染"する代わりに変数を使うことです(その考えが嫌いなら、この名前空間をスキップしてください)。私はトピックについて少なくとも半ダースの説明を見つけました(Googleには270000件以上のエントリがあります)。node.jsのプロトタイプ継承

var B = function() { 
    this.value = 2; 
    print(); 
} 
:私はこれは私が、私は次のようにさらに複雑なものを行うことを願ってどのように動作するかを発見したら

> 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) 

:ここ

は、私が最も有望なバリエーションが見つかりましたが、私は間違って何かを持っているものです

答えて

1

試してみてください。

b = new B(); 

この例は、期待どおりに動作します。

+0

素晴らしい!多くの感謝、あなたは私の日を救った – mark

2

あなたがする必要があるutil.inherits

+0

ヒントをお寄せいただきありがとうございます。私はutil.inheritsを非推奨とする議論を見てきました。なぜ私がこの例で使用したプロトタイプprototypeを好むのですか? – mark

+0

興味深い、リンクがありますか? –