ES6類的繼承方式有以下幾種:
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.
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.
let parent = {
name: "Alice",
sayHello: function() {
console.log(`Hello, ${this.name}!`);
}
};
let child = Object.create(parent);
child.sayHello(); // Output: Hello, Alice!
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!
需要注意的是,ES6類的繼承方式是單繼承的,即一個子類只能繼承一個父類。如果需要實現多繼承,則可以使用mixins的方式。