--- id: 587d7db2367417b2b2512b89 title: Use a Mixin to Add Common Behavior Between Unrelated Objects challengeType: 1 videoUrl: '' localeTitle: 使用Mixin在不相关的对象之间添加常见行为 --- ## Description
如您所见,行为通过继承来共享。但是,有些情况下继承不是最佳解决方案。对于像BirdAirplane这样的无关对象,继承不起作用。它们都可以飞行,但是Bird不是一种Airplane ,反之亦然。对于不相关的对象,最好使用mixinsmixin允许其他对象使用一组函数。
让flyMixin = function(obj){
obj.fly = function(){
console.log(“Flying,wooosh!”);
}
};
flyMixin接受任何对象并为其提供fly方法。
让bird = {
名称:“唐纳德”,
numLegs:2
};

让plane = {
型号:“777”,
numPassengers:524
};

flyMixin(鸟);
flyMixin(平面);
这里将birdplane传递给flyMixin ,然后将fly函数分配给每个对象。现在birdplane都可以飞行:
bird.fly(); //打印“飞行,嗖!”
plane.fly(); //打印“飞行,嗖!”
注意mixin如何允许相同的fly方法被不相关的对象birdplane重用。
## Instructions
创建一个名为glideMixinmixin ,它定义了一个名为glide的方法。然后使用glideMixinbirdboat都能够滑行。
## Tests
```yml tests: - text: 您的代码应该声明一个glideMixin变量,它是一个函数。 testString: 'assert(typeof glideMixin === "function", "Your code should declare a glideMixin variable that is a function.");' - text: 你的代码应该使用bird对象上的glideMixin来为它提供glide方法。 testString: 'assert(typeof bird.glide === "function", "Your code should use the glideMixin on the bird object to give it the glide method.");' - text: 你的代码应该使用boat对象上的glideMixin来为它提供glide方法。 testString: 'assert(typeof boat.glide === "function", "Your code should use the glideMixin on the boat object to give it the glide method.");' ```
## Challenge Seed
```js let bird = { name: "Donald", numLegs: 2 }; let boat = { name: "Warrior", type: "race-boat" }; // Add your code below this line ```
## Solution
```js // solution required ```