|
| 1 | +// ****************************** |
| 2 | +// Extends, Super, and Subclasses ****************************** |
| 3 | + |
| 4 | +console.log('Extends, Super, and Subclasses') |
| 5 | +console.log('\n') |
| 6 | + |
| 7 | +// Example 1 |
| 8 | +// class Cat { |
| 9 | +// constructor(name, age) { |
| 10 | +// this.name = name |
| 11 | +// this.age = age |
| 12 | +// } |
| 13 | + |
| 14 | +// eat() { |
| 15 | +// return `${this.name} is eating!` |
| 16 | +// } |
| 17 | +// meow() { |
| 18 | +// return 'MEOWWWW!!' |
| 19 | +// } |
| 20 | +// } |
| 21 | + |
| 22 | +// const monty = new Cat('monty', 9) |
| 23 | +// console.log(monty) |
| 24 | +// console.log(monty.meow()); |
| 25 | + |
| 26 | +console.log('\n') |
| 27 | +// Example 2 |
| 28 | +// class Dog { |
| 29 | +// constructor(name, age) { |
| 30 | +// this.name = name |
| 31 | +// this.age = age |
| 32 | +// } |
| 33 | +// eat() { |
| 34 | +// return `${this.name} is eating!` |
| 35 | +// } |
| 36 | +// bark() { |
| 37 | +// return 'WOOOF!' |
| 38 | +// } |
| 39 | +// } |
| 40 | + |
| 41 | +// const wyatt = new Dog('wyatt', 13) |
| 42 | +// console.log(wyatt) |
| 43 | +// console.log(wyatt.bark()); |
| 44 | + |
| 45 | +console.log('\n') |
| 46 | +// Example 3 |
| 47 | +// Parent class |
| 48 | +class Pet { |
| 49 | + constructor(name, age) { |
| 50 | + console.log('IN PET CONSTRUCTOR!') |
| 51 | + this.name = name |
| 52 | + this.age = age |
| 53 | + } |
| 54 | + eat() { |
| 55 | + return `${this.name} is eating!` |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +class Cat extends Pet { |
| 60 | + constructor(name, age, livesLeft = 9) { |
| 61 | + console.log('IN CAT CONSTRUCTOR!'); |
| 62 | + // Super is going to reference the class that we are extending from |
| 63 | + // Is going to call Pet constructor |
| 64 | + super(name, age) |
| 65 | + } |
| 66 | + meow() { |
| 67 | + return 'MEOWWWW!!' |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +class Dog extends Pet { |
| 72 | + bark() { |
| 73 | + return 'WOOOF!' |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +const monty = new Cat('monty', 9) |
| 78 | +console.log(monty) |
| 79 | +console.log(monty.meow()) |
| 80 | +console.log(monty.eat()) |
| 81 | + |
| 82 | +console.log('\n') |
| 83 | +const wyatt = new Dog('wyatt', 13) |
| 84 | +console.log(wyatt) |
| 85 | +console.log(wyatt.bark()) |
| 86 | +console.log(wyatt.eat()) |
| 87 | + |
| 88 | +console.log('\n') |
0 commit comments