1// Class Inheritance in JavaScript
2class Mammal {
3 constructor(name) {
4 this.name = name;
5 }
6 eats() {
7 return `${this.name} eats Food`;
8 }
9}
10
11class Dog extends Mammal {
12 constructor(name, owner) {
13 super(name);
14 this.owner = owner;
15 }
16 eats() {
17 return `${this.name} eats Chicken`;
18 }
19}
20
21let myDog = new Dog("Spot", "John");
22console.log(myDog.eats()); // Spot eats chicken
1function inherit(c, p) {
2 Object.defineProperty(c, 'prototype', {
3 value: Object.assign(c.prototype, p.prototype),
4 writable: true,
5 enumerable: false
6 });
7
8 Object.defineProperty(c.prototype, 'constructor', {
9 value: c,
10 writable: true,
11 enumerable: false
12 });
13 }
14// Or if you want multiple inheritance
15
16function _inherit(c, ...p) {
17 p.forEach(item => {
18 Object.defineProperty(c, 'prototype', {
19 value: Object.assign(c.prototype, item.prototype),
20 writable: true,
21 enumerable: false
22 });
23 })
24
25 Object.defineProperty(c.prototype, 'constructor', {
26 value: c,
27 writable: true,
28 enumerable: false
29 });
30 }