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 extends
the 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 super
the 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