Don't Repeat Yourself
,常以缩写形式DRY
出现,意思是“不要自己重复”。编写重复代码会产生的问题是:任何改变都需要去多个地方修复所有重复的代码。这通常意味着我们需要做更多的工作,会产生更高的出错率。
请观察下面的示例,Bird
和Dog
共享describe
方法:
```js
Bird.prototype = {
constructor: Bird,
describe: function() {
console.log("My name is " + this.name);
}
};
Dog.prototype = {
constructor: Dog,
describe: function() {
console.log("My name is " + this.name);
}
};
```
我们可以看到describe
方法在两个地方重复定义了。根据以上所说的DRY
原则,我们可以通过创建一个Animal 超类(或者父类)
来重写这段代码:
```js
function Animal() { };
Animal.prototype = {
constructor: Animal,
describe: function() {
console.log("My name is " + this.name);
}
};
```
Animal
构造函数中定义了describe
方法,可将Bird
和Dog
这两个构造函数的方法删除掉:
```js
Bird.prototype = {
constructor: Bird
};
Dog.prototype = {
constructor: Dog
};
```
Cat
和Bear
重复定义了eat
方法。本着DRY
的原则,通过将eat
方法移动到Animal 超类
中来重写你的代码。
Animal.prototype
应该有eat
属性。
testString: assert(Animal.prototype.hasOwnProperty('eat'));
- text: Bear.prototype
不应该有eat
属性。
testString: assert(!(Bear.prototype.hasOwnProperty('eat')));
- text: Cat.prototype
不应该有eat
属性。
testString: assert(!(Cat.prototype.hasOwnProperty('eat')));
```