prototype object from a supertype constructor function can still have its own methods in addition to inherited methods.
For example, Bird is a constructor that inherits its prototype from Animal:
function Animal() { }In addition to what is inherited from
Animal.prototype.eat = function() {
console.log("nom nom nom");
};
function Bird() { }
Bird.prototype = Object.create(Animal.prototype);
Bird.prototype.constructor = Bird;
Animal, you want to add behavior that is unique to Bird objects. Here, Bird will get a fly() function. Functions are added to Bird's prototype the same way as any constructor function:
Bird.prototype.fly = function() {Now instances of
console.log("I'm flying!");
};
Bird will have both eat() and fly() methods:
let duck = new Bird();
duck.eat(); // prints "nom nom nom"
duck.fly(); // prints "I'm flying!"
Dog object inherits from Animal and the Dog's prototype constructor is set to Dog. Then add a bark() method to the Dog object so that beagle can both eat() and bark(). The bark() method should print "Woof!" to the console.
Animal should not respond to the bark() method.
testString: assert(typeof Animal.prototype.bark == "undefined", 'Animal should not respond to the bark() method.');
- text: Dog should inherit the eat() method from Animal.
testString: assert(typeof Dog.prototype.eat == "function", 'Dog should inherit the eat() method from Animal.');
- text: Dog should have the bark() method as an own property.
testString: assert(Dog.prototype.hasOwnProperty('bark'), 'Dog should have the bark() method as an own property.');
- text: beagle should be an instanceof Animal.
testString: assert(beagle instanceof Animal, 'beagle should be an instanceof Animal.');
- text: The constructor for beagle should be set to Dog.
testString: assert(beagle.constructor === Dog, 'The constructor for beagle should be set to Dog.');
```