2016-12-01 146 views
7

我是學習JavaScript概念的新手。想要了解原型繼承如何工作。我的印象是,如果你的類繼承了它的父類,並且在兩個類的原型中有相同的命名方法,那麼當你在子實例上調用該方法時,子類原型中的方法將被調用。JavaScript原型覆蓋

代碼:

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

在調用cat1.printName()我預期的日誌「在貓的原型貓」,但它記錄的「動物原型貓」。有人可以向我解釋原因嗎?謝謝。

回答

7

你是對的,但是當你重置Cat.prototype時,你自己的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); 
 
} 
 

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