prototype
: ChildObject.prototype = Object.create (ParentObject.prototype);Luego,
ChildObject
recibió sus propios métodos encadenándolos 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. Aquí hay un ejemplo de Bird
anula el método eat()
heredado de Animal
: función animal () {}Si tienes una instancia,
Animal.prototype.eat = function () {
devuelve "nom nom nom";
};
función Bird () {}
// Heredar todos los métodos de Animal
Bird.prototype = Object.create (Animal.prototype);
// Bird.eat () anula Animal.eat ()
Bird.prototype.eat = function () {
devuelve "peck peck peck";
};
let duck = new Bird();
y llamas a duck.eat()
, así es como JavaScript busca el método en duck's
cadena de prototype
duck's
: 1. pato => ¿Se define eat () aquí? No. 2. Pájaro => ¿Se define comer () 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. fly()
de Penguin
para que devuelva "¡Ay !, este es un pájaro que no vuela". penguin.fly()
debería devolver la cadena "¡Ay !, este es un pájaro que no vuela".'
testString: 'assert(penguin.fly() === "Alas, this is a flightless bird.", "penguin.fly()
should return the string "Alas, this is a flightless bird."");'
- text: El método bird.fly()
debería devolver "Estoy volando!"
testString: 'assert((new Bird()).fly() === "I am flying!", "The bird.fly()
method should return "I am flying!"");'
```