Files
freeCodeCamp/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/override-inherited-methods.spanish.md
2018-10-08 13:34:43 -04:00

3.3 KiB

id, title, localeTitle, challengeType
id title localeTitle challengeType
587d7db1367417b2b2512b88 Override Inherited Methods Anular métodos heredados 1

Description

En las lecciones anteriores, aprendió que un objeto puede heredar su comportamiento (métodos) de otro objeto clonando su objeto prototype :
ChildObject.prototype = Object.create(ParentObject.prototype);
Luego, ChildObject recibió sus propios métodos al encadenarlos a su prototype :
ChildObject.prototype.methodName = function() {...};
Es posible anular un método heredado. Se realiza de la misma manera: agregando un método a ChildObject.prototype utilizando el mismo nombre de método que el que se anula. Este es un ejemplo de Bird anula el método eat() heredado de Animal :
function Animal() { }
Animal.prototype.eat = function() {
  return "nom nom nom";
};
function Bird() { }

// Inherit all methods from Animal
Bird.prototype = Object.create(Animal.prototype);

// Bird.eat() overrides Animal.eat()
Bird.prototype.eat = function() {
  return "peck peck peck";
};
Si tienes una instancia, let duck = new Bird(); y llama a duck.eat() , así es como JavaScript busca el método en duck's cadena de prototype duck's : 1. duck => ¿Se define eat () aquí? No. 2. Pájaro => ¿Se define eat () aquí? => Sí. Ejecutarlo y dejar de buscar. 3. Animal => eat () también está definido, pero JavaScript dejó de buscar antes de alcanzar este nivel. 4. Objeto => JavaScript dejó de buscar antes de alcanzar este nivel.

Instructions

Anula el método fly() de Penguin para que devuelva "¡Ay !, este es un pájaro que no vuela".

Tests

tests:
  - text: &#39; <code>penguin.fly()</code> debería devolver la cadena &quot;¡Ay !, este es un pájaro que no vuela».
    testString: 'assert(penguin.fly() === "Alas, this is a flightless bird.", "<code>penguin.fly()</code> should return the string "Alas, this is a flightless bird."");'
  - text: El método <code>bird.fly()</code> debería devolver &quot;Estoy volando!&quot;
    testString: 'assert((new Bird()).fly() === "I am flying!", "The <code>bird.fly()</code> method should return "I am flying!"");'

Challenge Seed

function Bird() { }

Bird.prototype.fly = function() { return "I am flying!"; };

function Penguin() { }
Penguin.prototype = Object.create(Bird.prototype);
Penguin.prototype.constructor = Penguin;

// Add your code below this line



// Add your code above this line

let penguin = new Penguin();
console.log(penguin.fly());

Solution

function Bird() { }

Bird.prototype.fly = function() { return "I am flying!"; };

function Penguin() { }
Penguin.prototype = Object.create(Bird.prototype);
Penguin.prototype.constructor = Penguin;
Penguin.prototype.fly = () => 'Alas, this is a flightless bird.';
let penguin = new Penguin();
console.log(penguin.fly());