Don't Repeat Yourself (DRY) 。重复代码是一个问题的原因是因为任何更改都需要在多个位置修复代码。这通常意味着为程序员提供更多工作,并且有更多错误空间。请注意,在下面的示例中, describe方法由Bird和Dog共享: Bird.prototype = {
构造函数:Bird,
describe:function(){
console.log(“我的名字是”+ this.name);
}
};
Dog.prototype = {
构造函数:狗,
describe:function(){
console.log(“我的名字是”+ this.name);
}
};
describe方法在两个地方重复。可以通过创建名为Animal的supertype (或父级)来编辑代码以遵循DRY原则: function Animal(){};由于
Animal.prototype = {
构造函数:Animal,
describe:function(){
console.log(“我的名字是”+ this.name);
}
};
Animal包含describe方法,您可以从Bird和Dog删除它: Bird.prototype = {
构造函数:Bird
};
Dog.prototype = {
构造函数:狗
};
Cat和Bear都重复eat 。通过将eat方法移动到Animal supertype以DRY的精神编辑代码。 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.");'
```