This includes certificates (where it does nothing), but does not include any translations.
2.9 KiB
2.9 KiB
id, title, challengeType, isHidden, forumTopicId
| id | title | challengeType | isHidden | forumTopicId |
|---|---|---|---|---|
| 587d7db0367417b2b2512b83 | Use Inheritance So You Don't Repeat Yourself | 1 | false | 301334 |
Description
describe method is shared by Bird and Dog:
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);
}
};
The 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() { };
Animal.prototype = {
constructor: Animal,
describe: function() {
console.log("My name is " + this.name);
}
};
Since 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'));
- text: <code>Bear.prototype</code> should not have the <code>eat</code> property.
testString: assert(!(Bear.prototype.hasOwnProperty('eat')));
- text: <code>Cat.prototype</code> should not have the <code>eat</code> property.
testString: assert(!(Cat.prototype.hasOwnProperty('eat')));
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");
}
};