2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Add Methods After Inheritance
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Add Methods After Inheritance
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
---
|
|
|
|
## Problem Explanation
|
2018-10-12 15:37:13 -04:00
|
|
|
|
|
|
|
Just like the following example, a new instance of an object - `Dog` - must be created and the `prototype` must be set.
|
|
|
|
|
|
|
|
```javascript
|
2019-07-24 00:59:27 -07:00
|
|
|
function Bird() {}
|
2018-10-12 15:37:13 -04:00
|
|
|
Bird.prototype = Object.create(Animal.prototype);
|
|
|
|
Bird.prototype.constructor = Bird;
|
|
|
|
```
|
|
|
|
|
|
|
|
Then a new function - `bark()` - must be added to the Dog prototype.
|
|
|
|
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
---
|
|
|
|
## Solutions
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
```javascript
|
|
|
|
function Animal() {}
|
|
|
|
Animal.prototype.eat = function() {
|
|
|
|
console.log("nom nom nom");
|
|
|
|
};
|
|
|
|
|
|
|
|
function Dog() {}
|
2018-10-12 15:37:13 -04:00
|
|
|
|
|
|
|
// Add your code below this line
|
|
|
|
Dog.prototype = Object.create(Animal.prototype);
|
|
|
|
Dog.prototype.constructor = Dog;
|
|
|
|
Dog.prototype.bark = function() {
|
2019-07-24 00:59:27 -07:00
|
|
|
console.log("Woof woof!");
|
2018-10-12 15:37:13 -04:00
|
|
|
};
|
|
|
|
// Add your code above this line
|
|
|
|
|
|
|
|
let beagle = new Dog();
|
|
|
|
|
|
|
|
beagle.eat(); // Should print "nom nom nom"
|
|
|
|
beagle.bark(); // Should print "Woof!"
|
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
</details>
|