how to use extends in javascript

In order to create inheritance in JavaScript, you can use the extends keyword. This allows you to create a child class that inherits properties and methods from a parent class.

Here's an example:

index.tsx
class Animal {
  constructor(name) {
    this.name = name;
  }

  sayName() {
    console.log(`My name is ${this.name}`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }

  sayBreed() {
    console.log(`My breed is ${this.breed}`);
  }
}

const myDog = new Dog("Fido", "Labrador Retriever");
myDog.sayName(); // output: "My name is Fido"
myDog.sayBreed(); // output: "My breed is Labrador Retriever"
460 chars
25 lines

In this example, Animal is the parent class and Dog is the child class that extends from Animal. The extends keyword is used to create this relationship.

The super keyword within the Dog class constructor is used to call the parent class constructor and pass in the name argument, which is then set as a property on the Dog instance.

Dog class also has a sayBreed method which is unique to it.

This is just a basic example, but extends and classes can add a lot of flexibility and organization to your JavaScript code.

gistlibby LogSnag