Class
1.How to implement inheritance in JavaScript?
In JavaScript, we can implement inheritance using either prototype-based inheritance or class-based inheritance. Here's an example of both approaches:
Prototype-based inheritance
// parent constructor
function Animal(name) {
this.name = name;
}
// parent method
Animal.prototype.sayHello = function () {
console.log("Hello, I'm " + this.name);
};
// child constructor
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
// child inherits from parent
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// child method
Dog.prototype.bark = function () {
console.log("Woof!");
};
// create a dog instance and call methods
var dog = new Dog("Fido", "Labrador");
dog.sayHello(); // "Hello, I'm Fido"
dog.bark(); // "Woof!"In the above example, we define a parent Animal constructor and a sayHello method on its prototype. Then we define a child Dog constructor that inherits from Animal using Object.create. We also define a bark method on the Dog prototype. Finally, we create a Dog instance and call its methods.
Class-based inheritance
// parent class
class Animal {
constructor(name) {
this.name = name;
}
// parent method
sayHello() {
console.log(`Hello, I'm ${this.name}`);
}
}
// child class
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
// child method
bark() {
console.log("Woof!");
}
}
// create a dog instance and call methods
var dog = new Dog("Fido", "Labrador");
dog.sayHello(); // "Hello, I'm Fido"
dog.bark(); // "Woof!"In the above example, we define a parent Animal class and a sayHello method. Then we define a child Dog class that extends Animal. We also define a bark method on the Dog class. Finally, we create a Dog instance and call its methods.
Both approaches allow us to reuse code and implement inheritance in JavaScript. However, class-based inheritance is often preferred because it is more familiar to developers coming from other object-oriented languages.