2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Use Inheritance So You Don't Repeat Yourself
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Use Inheritance So You Don't Repeat Yourself
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
---
|
|
|
|
## Solutions
|
|
|
|
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
2018-10-12 15:37:13 -04:00
|
|
|
|
|
|
|
```javascript
|
|
|
|
function Cat(name) {
|
2019-07-24 00:59:27 -07:00
|
|
|
this.name = name;
|
|
|
|
}
|
2018-10-12 15:37:13 -04:00
|
|
|
|
|
|
|
Cat.prototype = {
|
|
|
|
constructor: Cat
|
|
|
|
};
|
|
|
|
|
|
|
|
function Bear(name) {
|
2019-07-24 00:59:27 -07:00
|
|
|
this.name = name;
|
|
|
|
}
|
2018-10-12 15:37:13 -04:00
|
|
|
|
|
|
|
Bear.prototype = {
|
|
|
|
constructor: Bear
|
|
|
|
};
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
function Animal() {}
|
2018-10-12 15:37:13 -04:00
|
|
|
|
|
|
|
Animal.prototype = {
|
|
|
|
constructor: Animal,
|
|
|
|
eat: function() {
|
|
|
|
console.log("nom nom nom");
|
|
|
|
}
|
|
|
|
};
|
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
#### Code Explanation
|
|
|
|
* Remove the "eat" method from Cat.prototype and Bear.prototype and add it to the Animal.prototype.
|
|
|
|
</details>
|