prototype
de una función constructora de supertype
aún puede tener sus propios métodos además de los métodos heredados. Por ejemplo, Bird
es un constructor que hereda su prototype
de Animal
: función animal () {}Además de lo que se hereda de
Animal.prototype.eat = function () {
console.log ("nom nom nom");
};
función Bird () {}
Bird.prototype = Object.create (Animal.prototype);
Bird.prototype.constructor = Bird;
Animal
, desea agregar un comportamiento que sea exclusivo de los objetos Bird
. Aquí, Bird
obtendrá una función fly()
. Las funciones se agregan al prototype
Bird's
la misma manera que cualquier función de constructor: Bird.prototype.fly = function () {Ahora las instancias de
console.log ("Estoy volando!");
};
Bird
tendrán los métodos de eat()
y fly()
: dejar pato = nuevo pájaro ();
duck.eat (); // imprime "nom nom nom"
duck.fly (); // impresiones "Estoy volando!"
Dog
hereda de Animal
y el constructor Dog's
prototype
Dog's
esté configurado en Dog. Luego, agregue un método de bark()
al objeto Dog
para que el beagle
pueda eat()
y bark()
. El método de la bark()
debe imprimir "¡Guau!" a la consola. Animal
no debe responder al método de la bark()
.
testString: 'assert(typeof Animal.prototype.bark == "undefined", "Animal
should not respond to the bark()
method.");'
- text: Dog
debe heredar el método de eat()
de Animal
.
testString: 'assert(typeof Dog.prototype.eat == "function", "Dog
should inherit the eat()
method from Animal
.");'
- text: Dog
debe tener el método de la bark()
como propiedad own
.
testString: 'assert(Dog.prototype.hasOwnProperty("bark"), "Dog
should have the bark()
method as an own
property.");'
- text: beagle
debe ser un instanceof
Animal
.
testString: 'assert(beagle instanceof Animal, "beagle
should be an instanceof
Animal
.");'
- text: El constructor para beagle
debe establecer en Dog
.
testString: 'assert(beagle.constructor === Dog, "The constructor for beagle
should be set to Dog
.");'
```