2016-09-29 1 views
0

が動作していない:Javascriptを:Object.Create(プロトタイプ)は、私がNode.jsの中で次のことを実行しています

function TextCell(text) { 
    this.text = text.split("\n"); 
} 

TextCell.prototype.minWidth = function() { 
    return this.text.reduce(function(width, line) { 
     return Math.max(width, line.length); 
    }, 0); 
}; 

TextCell.prototype.minHeight = function() { 
    return this.text.length; 
}; 

TextCell.prototype.draw = function(width, height) { 
    var result = []; 
    for (var i = 0; i < height; i++) { 
     var line = this.text[i] || ""; 
     result.push(line + repeat(" ", width - line.length)); 
    } 
    return result; 
}; 

function RTextCell(text) { 
    TextCell.call(this, text); 
} 

RTextCell.prototype = Object.create(TextCell.prototype); 

RTextCell.prototype.draw = function(width, height) { 
    var result = []; 
    for (var i = 0; i < height; i++) { 
     var line = this.text[i] || ""; 
     result.push(repeat(" ", width - line.length) + line); 
    } 
    return result; 
}; 

私は(RTextCell.prototype)にconsole.logとき、私は唯一の引き分けでプロトタイプを取得します関数。また、私は(Object.create(Textcell.prototype))私はちょうど "TextCell {}"を取得するログを記録します。なぜプロトタイプのクローンが空であるように見えますか?

編集:私の間違いに気づいた。 RTextCell型のオブジェクトを定義する前に作成しました。そういうわけで、プロトタイプが空になったのです。ここにその部分を含めないと申し訳ありません

+0

[あなたのコードはうまくいくようです。](https://jsfiddle.net/1oypy93n/)プロトタイプが渡された引数である新しいオブジェクトを作成していることに注意してください。 Chromeで表示している場合は、 '__proto__'プロパティを調べて基礎となるプロトタイプを確認してください。 –

+0

node.jsで実行しています同じ関数が定義されている両方のクラスに依存する関数を使用しようとするとエラーが発生する – miracleJester

答えて

1

なぜプロトタイプのクローンが空であるように見えますか?

自身のプロパティがないためです。継承されたプロパティはコンソールには直接表示されませんが、オブジェクトを展開すると、プロトタイプチェーンに従うことができます。

関連する問題