What are the different ways to inherit in ES6 classes?
There are several ways to inherit in ES6 classes:
- Implement class inheritance using the keyword “extends”: With the “extends” keyword, a class can inherit the properties and methods of another class. For example:
class Parent {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, ${this.name}!`);
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
sayAge() {
console.log(`I'm ${this.age} years old.`);
}
}
let child = new Child("Alice", 10);
child.sayHello(); // Output: Hello, Alice!
child.sayAge(); // Output: I'm 10 years old.
- Using the super keyword to call a parent class method: In a subclass, you can use the super keyword to call the constructor and methods of the parent class. For example:
class Parent {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, ${this.name}!`);
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
sayHello() {
super.sayHello();
console.log("How are you?");
}
sayAge() {
console.log(`I'm ${this.age} years old.`);
}
}
let child = new Child("Alice", 10);
child.sayHello(); // Output: Hello, Alice! How are you?
child.sayAge(); // Output: I'm 10 years old.
- Implementing prototype chain inheritance using Object.create() method: By using the Object.create() method, you can create a new object and set its prototype to another object. For example:
let parent = {
name: "Alice",
sayHello: function() {
console.log(`Hello, ${this.name}!`);
}
};
let child = Object.create(parent);
child.sayHello(); // Output: Hello, Alice!
- Achieving multiple inheritance using mixins involves combining the properties and methods of multiple objects into a new object. For example:
let mixin1 = {
sayHello: function() {
console.log("Hello!");
}
};
let mixin2 = {
sayGoodbye: function() {
console.log("Goodbye!");
}
};
class MyClass {}
Object.assign(MyClass.prototype, mixin1, mixin2);
let obj = new MyClass();
obj.sayHello(); // Output: Hello!
obj.sayGoodbye(); // Output: Goodbye!
It is important to note that in ES6, class inheritance is single inheritance, meaning a subclass can only inherit from one parent class. If you need to implement multiple inheritance, you can use mixins.