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.");'
```