--- id: 587d7db0367417b2b2512b83 title: Use Inheritance So You Don't Repeat Yourself challengeType: 1 videoUrl: '' localeTitle: 使用继承,所以你不要重复自己 --- ## Description
编程中有一个原则叫做“ Don't Repeat Yourself (DRY) 。重复代码是一个问题的原因是因为任何更改都需要在多个位置修复代码。这通常意味着为程序员提供更多工作,并且有更多错误空间。请注意,在下面的示例中, describe方法由BirdDog共享:
Bird.prototype = {
构造函数:Bird,
describe:function(){
console.log(“我的名字是”+ this.name);
}
};

Dog.prototype = {
构造函数:狗,
describe:function(){
console.log(“我的名字是”+ this.name);
}
};
describe方法在两个地方重复。可以通过创建名为Animalsupertype (或父级)来编辑代码以遵循DRY原则:
function Animal(){};

Animal.prototype = {
构造函数:Animal,
describe:function(){
console.log(“我的名字是”+ this.name);
}
};
由于Animal包含describe方法,您可以从BirdDog删除它:
Bird.prototype = {
构造函数:Bird
};

Dog.prototype = {
构造函数:狗
};
## Instructions
CatBear都重复eat 。通过将eat方法移动到Animal supertypeDRY的精神编辑代码。
## Tests
```yml tests: - text: Animal.prototype应该有eat属性。 testString: 'assert(Animal.prototype.hasOwnProperty("eat"), "Animal.prototype should have the eat property.");' - text: Bear.prototype不应该有eat属性。 testString: 'assert(!(Bear.prototype.hasOwnProperty("eat")), "Bear.prototype should not have the eat property.");' - text: Cat.prototype不应该有eat属性。 testString: 'assert(!(Cat.prototype.hasOwnProperty("eat")), "Cat.prototype should not have the eat property.");' ```
## 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 // solution required ```