【002JavaScript class inheritance】Knowledge of basic inheritance, calling parent class methods, and mix-in patterns. Master the concepts and skills of class inheritance to improve code flexibility and maintainability.

JavaScript class inheritance

In JavaScript, class inheritance is an important concept for code reuse and extension. Through inheritance, we can create new classes based on existing classes and inherit the properties and methods of the parent class. This article will detail various aspects and techniques of JavaScript class inheritance.

1. Basic inheritance

Basic class inheritance can be achieved using extendsthe keyword .


  class Animal {
    constructor(name) {
      this.name = name;
    }
speak() {
  console.log(`The ${this.name} makes a sound.`);
}

}

class Dog extends Animal {
bark() {
console.log(${this.name} barks loudly.);
}
}

let dog = new Dog(“Fido”);
dog.speak(); // 输出: The Fido makes a sound.
dog.bark(); // 输出: Fido barks loudly.

2. Call the parent class method

By using superthe keyword , we can call the method of the parent class in the child class.


  class Animal {
    constructor(name) {
      this.name = name;
    }
speak() {
  console.log(`The ${this.name} makes a sound.`);
}

}

class

Guess you like

Origin blog.csdn.net/qq_43797491/article/details/131091217