3.4 KiB
3.4 KiB
id, title, challengeType
id | title | challengeType |
---|---|---|
587d7db0367417b2b2512b83 | Use Inheritance So You Don't Repeat Yourself | 1 |
Description
Don't Repeat Yourself (DRY)
. The reason repeated code is a problem is because any change requires fixing code in multiple places. This usually means more work for programmers and more room for errors.
Notice in the example below that the describe
method is shared by Bird
and Dog
:
Bird.prototype = {The
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
method is repeated in two places. The code can be edited to follow the DRY
principle by creating a supertype
(or parent) called Animal
:
function Animal() { };Since
Animal.prototype = {
constructor: Animal,
describe: function() {
console.log("My name is " + this.name);
}
};
Animal
includes the describe
method, you can remove it from Bird
and Dog
:
Bird.prototype = {
constructor: Bird
};
Dog.prototype = {
constructor: Dog
};
Instructions
eat
method is repeated in both Cat
and Bear
. Edit the code in the spirit of DRY
by moving the eat
method to the Animal
supertype
.
Tests
tests:
- text: <code>Animal.prototype</code> should have the <code>eat</code> property.
testString: 'assert(Animal.prototype.hasOwnProperty("eat"), "<code>Animal.prototype</code> should have the <code>eat</code> property.");'
- text: <code>Bear.prototype</code> should not have the <code>eat</code> property.
testString: 'assert(!(Bear.prototype.hasOwnProperty("eat")), "<code>Bear.prototype</code> should not have the <code>eat</code> property.");'
- text: <code>Cat.prototype</code> should not have the <code>eat</code> property.
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
function Cat(name) {
this.name = name;
}
Cat.prototype = {
constructor: Cat
};
function Bear(name) {
this.name = name;
}
Bear.prototype = {
constructor: Bear
};
function Animal() { }
Animal.prototype = {
constructor: Animal,
eat: function() {
console.log("nom nom nom");
}
};