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的方式。