mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-15 22:01:59 -04:00
3.6 KiB
3.6 KiB
id, title, localeTitle, challengeType
| id | title | localeTitle | challengeType |
|---|---|---|---|
| 587d7db0367417b2b2512b83 | Use Inheritance So You Don't Repeat Yourself | Usa la herencia para que no te repitas | 1 |
Description
Don't Repeat Yourself (DRY) . La razón por la cual el código repetido es un problema es porque cualquier cambio requiere un código de corrección en varios lugares. Esto generalmente significa más trabajo para los programadores y más espacio para errores.
Observe en el siguiente ejemplo que Bird y Dog comparten el método de describe :
Bird.prototype = {El método
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 se repite en dos lugares. El código se puede editar para seguir el principio DRY creando un supertype (o padre) llamado Animal :
function Animal() { };Dado que
Animal.prototype = {
constructor: Animal,
describe: function() {
console.log("My name is " + this.name);
}
};
Animal incluye el método de describe , puedes eliminarlo de Bird and Dog :
Bird.prototype = {
constructor: Bird
};
Dog.prototype = {
constructor: Dog
};
Instructions
eat se repite tanto en Cat como en Bear . Edite el código en el espíritu de DRY moviendo el método de eat al supertype Animal .
Tests
tests:
- text: <code>Animal.prototype</code> debe tener la propiedad <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> no debe tener la propiedad <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> no debe tener la propiedad <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
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");
}
};