0%

javascript-class-multiple-inheritance

介绍

ES6以后有了class关键字,可以方便地实现类的继承。但是JavaScript是一门单继承的语言,即一个类只能继承一个类。但是有时候我们需要多继承,这时候我们可以使用混入(mixin)来实现多继承。

混入

混入是一种实现多继承的方式,即将多个类的方法混入到一个类中。下面是一个简单的混入实现,它对应一个现实中的例子,比如鸭子可以飞也可以游泳,我们可以将飞行和游泳的行为抽象成两个mixin,然后将它们混入到鸭子类中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function mix(...mixins) {
class Mix {}
for (let mixin of mixins) {
Object.assign(Mix.prototype, mixin);
}
return Mix;
}

// 定义两个mixin
const Flyable = {
fly() { console.log("I can fly!"); }
};

const Swimmable = {
swim() { console.log("I can swim!"); }
};

// 创建一个使用mixin的类
class Duck extends mix(Flyable, Swimmable) {}

let duck = new Duck();
duck.fly(); // 输出: I can fly!
duck.swim(); // 输出: I can swim!

组合

组合也是一种实现多重继承的方式,即通过组合多个类的实例来实现多继承。下面的代码使用组合来实现鸭子可以飞和游泳的功能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class FlyBehavior {
fly() { console.log("I can fly!"); }
}

class SwimBehavior {
swim() { console.log("I can swim!"); }
}

class Duck {
constructor() {
this.flyBehavior = new FlyBehavior();
this.swimBehavior = new SwimBehavior();
}

performFly() { this.flyBehavior.fly(); }
performSwim() { this.swimBehavior.swim(); }
}

let duck = new Duck();
duck.performFly(); // 输出: Flying with wings!
duck.performSwim(); // 输出: Swimming!