2016-12-01 3 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

Вы правы, но ваше переопределение функции 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

Смежные вопросы