Introduction
ES6以后有了class关键字,可以方便地实现类的继承。但是JavaScript是一门单继承的语言,即一个类只能继承一个类。但是有时候我们需要多继承,这时候我们可以使用混入(mixin)来实现多继承。
Mixin
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; }
const Flyable = { fly() { console.log("I can fly!"); } };
const Swimmable = { swim() { console.log("I can swim!"); } };
class Duck extends mix(Flyable, Swimmable) {}
let duck = new Duck(); duck.fly(); duck.swim();
|
Composition
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("Flying with wings!"); } }
class SwimBehavior { swim() { console.log("Swimming!"); } }
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(); duck.performSwim();
|