--- id: 587d7db0367417b2b2512b83 title: Use Inheritance So You Don't Repeat Yourself challengeType: 1 forumTopicId: 301334 localeTitle: Используйте Наследование, чтобы вы не повторяли себя --- ## Description
В программировании есть принцип « Don't Repeat Yourself (DRY) . Причина повторного кода - проблема, потому что для любого изменения требуется код исправления в нескольких местах. Это обычно означает больше работы для программистов и больше возможностей для ошибок. В приведенном ниже примере обратите внимание, что метод describe разделяет Bird and Dog :
Bird.prototype = {
конструктор: Птица,
Опишите: function () {
console.log («Мое имя» + this.name);
}
};

Dog.prototype = {
конструктор: Собака,
Опишите: function () {
console.log («Мое имя» + this.name);
}
};
Метод describe повторяется в двух местах. Код можно редактировать, чтобы следовать принципу DRY , создав supertype (или родительский элемент) под названием Animal :
функция Animal () {};

Animal.prototype = {
конструктор: Animal,
Опишите: function () {
console.log («Мое имя» + this.name);
}
};
Поскольку Animal включает метод describe , вы можете удалить его из Bird and Dog :
Bird.prototype = {
конструктор: Птица
};

Dog.prototype = {
конструктор: Собака
};
## Instructions
Метод eat повторяется как у Cat и у Bear . Измените код в духе DRY , переместив метод eat на supertype Animal .
## Tests
```yml tests: - text: Animal.prototype should have the eat property. testString: assert(Animal.prototype.hasOwnProperty('eat')); - text: Bear.prototype should not have the eat property. testString: assert(!(Bear.prototype.hasOwnProperty('eat'))); - text: Cat.prototype should not have the eat property. testString: assert(!(Cat.prototype.hasOwnProperty('eat'))); ```
## Challenge Seed
```js function Cat(name) { this.name = name; } Cat.prototype = { constructor: Cat, eat: function() { console.log("nom nom nom"); } }; function Bear(name) { this.name = name; } Bear.prototype = { constructor: Bear, eat: function() { console.log("nom nom nom"); } }; function Animal() { } Animal.prototype = { constructor: Animal, }; ```
## Solution
```js function Cat(name) { this.name = name; } Cat.prototype = { constructor: Cat }; function Bear(name) { this.name = name; } Bear.prototype = { constructor: Bear }; function Animal() { } Animal.prototype = { constructor: Animal, eat: function() { console.log("nom nom nom"); } }; ```