3.0 KiB
3.0 KiB
id, title, challengeType, videoUrl, localeTitle
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
587d7db0367417b2b2512b83 | Use Inheritance So You Don't Repeat Yourself | 1 | 使用继承,所以你不要重复自己 |
Description
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 = {
构造函数:狗
};
Instructions
Cat
和Bear
都重复eat
。通过将eat
方法移动到Animal
supertype
以DRY
的精神编辑代码。 Tests
tests:
- text: <code>Animal.prototype</code>应该有<code>eat</code>属性。
testString: 'assert(Animal.prototype.hasOwnProperty("eat"), "<code>Animal.prototype</code> should have the <code>eat</code> property.");'
- text: <code>Bear.prototype</code>不应该有<code>eat</code>属性。
testString: 'assert(!(Bear.prototype.hasOwnProperty("eat")), "<code>Bear.prototype</code> should not have the <code>eat</code> property.");'
- text: <code>Cat.prototype</code>不应该有<code>eat</code>属性。
testString: 'assert(!(Cat.prototype.hasOwnProperty("eat")), "<code>Cat.prototype</code> should not have the <code>eat</code> property.");'
Challenge Seed
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
// solution required