We learned that when we build a class, we use a constructor to define the base variables, that can be accessed, with all of the methods of that class. Let's use the standard "dog", "cat" classes for demonstration:
- Javascript
- // Dog class
- class Dog {
- constructor ( name, age ) {
- this.name = name;
- this.age = age;
- }
- // create the age method
- age() {
- return `${this.name} is ${this.age} years old.`;
- }
- // create the eat method
- eat() {
- return `${this.name} is eating.`;
- }
- // create the meow method
- bark(){
- return `${this.name} goes Woof, Woof, Bark, Bark.`;
- }
- constructor ( name, age ) {
- }
- Javascript
- // Cat class
- class Cat {
- constructor ( name, age ) {
- this.name = name;
- this.age = age;
- }
- // create the age method
- age() {
- return `${this.name} is ${this.age} years old.`;
- }
- // create the eat method
- eat() {
- return `${this.name} is eating.`;
- }
- // create the bark method
- meow(){
- return `${this.name} goes Meeooww, purr, purr.';
- }
- constructor ( name, age ) {
- }
Now we can call:
- const Chico = Dog( 'Chico' );
- Chico.eat()
- Chico.bark()
And of course the Cat class would work exactly the same, except there is no meow method for the Dog class, and there is no bark method for the Cat class.
What's important to note here is that we've created two different classes, each with their own, individual constructor. We also notice that there is some duplication here between the two classes. Both classes share the same variables in their respective constructors, and the also share the eat() method.
Wouldn't it be nice if we could simplify the coding, and create a common constructor that would have all of the common elements included, that we could access from all of our individual classes? This is where Extends comes in.