2016-12-01 1 views
7

JavaScriptの概念を学ぶのが初めてです。プロトタイプの継承がどのように機能するかを理解したい。私の印象は、クラスが親を継承し、両方のクラスのプロトタイプに同じ名前のメソッドがある場合です。子インスタンスのメソッドを呼び出すと、その子プロトタイプのメソッドが呼び出されます。JavaScriptプロトタイプオーバーライド

コード:cat1.printNameを呼んで

function Animal(name) { 
    this.name = name; 
} 

Animal.prototype.printName = function() { 
    console.log(this.name + ' in animal prototype'); 
} 

function Cat(name) { 
    Animal.call(this, name); 
} 



Cat.prototype.printName = function() { 
    console.log(this.name + ' in cat prototype'); 
} 

Cat.prototype = Object.create(Animal.prototype); 

var anm1 = new Animal('mr cupcake'); 
anm1.printName(); 


var cat1 = new Cat('cat'); 
cat1.printName(); 

()私はそれが猫のプロトタイプで猫」をログに記録すると予想しかし、それは動物のプロトタイプで猫」をログに記録。誰かが私に理由を説明してもらえますか?ありがとう。

答えて

7

正しいですが、printName()関数のオーバーライド自体は、Cat.prototypeをリセットしたときに次の行でオーバーライドされます。単純にコードの順序を移動すると、この問題は修正されます。

function Animal(name) { 
 
    this.name = name; 
 
} 
 

 
Animal.prototype.printName = function() { 
 
    console.log(this.name + ' in animal prototype'); 
 
} 
 

 
function Cat(name) { 
 
    Animal.call(this, name); 
 
} 
 

 
// OLD LOCATION of code 
 

 
// This was overriding your override! 
 
// Setting the prototype of an object to another object 
 
// is the basis for JavaScript's prototypical inhertiance 
 
// This line replaces the existing prototype object (which is 
 
// where your override was) with a completely new object. 
 
Cat.prototype = Object.create(Animal.prototype); 
 

 
// NEW LOCATION 
 
// AFTER setting the prototype (and creating inheritance), 
 
// it is safe to do the override: 
 
Cat.prototype.printName = function() { 
 
    console.log(this.name + ' in cat prototype'); 
 
} 
 

 
var anm1 = new Animal('mr cupcake'); 
 
anm1.printName(); // "mr cupcake in animal prototype" 
 

 
var cat1 = new Cat('cat'); 
 
cat1.printName(); // "cat in cat prototype"

+0

は、説明のためにどうもありがとうございます。 – shilpi