2016-12-31 1 views
0

私はクイック検索を行いましたが、この質問に対する答えを見つけることはできません。継承するときに関数プロトタイプをコピーすることを指しています。 thisキーワードを使用する代わりに、コンストラクタ関数prototype objにプロパティを追加することをお勧めします。私は確信していない理由がありますが、私はJavaScriptのニュアンスをよりよく理解しようとしています。たとえば、通常のプロトタイプ継承では、これは "this"です。プロトタイプの継承とプロトタイプオブジェクトは、なぜこの程度まで使用されていませんか?

function Dog(name,age,breed){ 
     this.name=name; 
     this.age=age; 
     this.breed=breed; 
} 
Dog.prototype.bark=function(){console.log("bark bark bark");} 

let spike=new Dog("Spike",6,"lab"); 
let rover=new Dog("Rover",8,"poodle"); 


//^with the constructor function, no instance has the bark function but 
//but refers to the same function on the constructor prototype obj, so the 
//same function isn't being duplicated. However new keyword changes the 
//context of this to refer to the obj so these properties are duplicated 
//on every instance. 

//I'm curious as to the reason why new doesn't change this to refer to the 
//prototype obj for example and then have the instance refers its 
//constructor's prototype like with the bark function? 

//for example why isn't this a common pattern and what are the reasons I 
//should use it. 


function Dog(name,age,breed){ 
     Dog.prototype.name=name; 
     Dog.prototype.age=age; 
     Dog.prototype.breed=breed; 
} 

let spike=new Dog("Spike",6,"lab"); 
let rover=new Dog("rover",8,"poodle"); 


//I feel like the above code would be more DRY, I'm sure there is a reason 
// this isn't common and I'm curious as to why 
+0

あなたがあなたのやり方をするときに 'spike.name'が何であるかを見てみましょう。なぜ人々があなたのやり方をしないのかを知ることができます。 – user2357112

答えて

3

あなたはプロトタイプでpropertiesを持っている場合、あなたは以下の二つの文から、新しい値を持つプロパティにあなたがあなたの例では、クラスすなわちをインスタンス化するたびに上書きされますよると、ここで

let spike=new Dog("Spike",6,"lab"); 

let rover=new Dog("rover",8,"poodle"); 

spike.nameSpikeで、rover.nameroverである必要がありますが、このコードを実行してチェックすると、両方ともroverとなります。

spikeのプロパティは、新しいインスタンスroverを作成したときにroverというプロパティで上書きされます。 新しいインスタンスを作成し、プロパティをオーバーライドするたびに、プロトタイプに添付されている methodsまたはpropertiesのインスタンスが1回だけ作成され、新しいインスタンスが作成されるたびに継承されます。

コンストラクタ関数を作成するのは、Spikeroverのようにインスタンスごとに異なるプロパティがあるからです。メソッドの場合、メソッドは新しいインスタンスが作成されるたびに作成する必要がないすべてのインスタンスに対して再利用できるコンストラクタには一般的なので、thisというキーワードをコンストラクタで定義する代わりにprototypeにアタッチします。

関連する問題