2.8 KiB
2.8 KiB
id, title, challengeType, forumTopicId, localeTitle
id | title | challengeType | forumTopicId | localeTitle |
---|---|---|---|---|
587d7db2367417b2b2512b89 | Use a Mixin to Add Common Behavior Between Unrelated Objects | 1 | 301331 | 使用 Mixin 在不相关对象之间添加共同行为 |
Description
Bird
和Airplane
。虽然它们都可以飞行,但是Bird
并不是一种Airplane
,反之亦然。
对于不相关的对象,更好的方法是使用mixins
。mixin
允许其他对象使用函数集合。
let flyMixin = function(obj) {
obj.fly = function() {
console.log("Flying, wooosh!");
}
};
flyMixin
能接受任何对象,并为其提供fly
方法。
let bird = {
name: "Donald",
numLegs: 2
};
let plane = {
model: "777",
numPassengers: 524
};
flyMixin(bird);
flyMixin(plane);
这里的flyMixin
接收了bird
和plane
对象,然后将fly
方法分配给了每一个对象。现在bird
和plane
都可以飞行了:
bird.fly(); // prints "Flying, wooosh!"
plane.fly(); // prints "Flying, wooosh!"
注意观察mixin
是如何允许相同的fly
方法被不相关的对象bird
和plane
重用的。
Instructions
glideMixin
的mixin
,并定义一个glide
方法。然后使用glideMixin
来给bird
和boat
赋予滑行(glide)的能力。
Tests
tests:
- text: 你应该声明一个变量名为<code>glideMixin</code>的函数。
testString: assert(typeof glideMixin === "function");
- text: 你应该在<code>bird</code>上使用<code>glideMixin</code>,以提供<code>glide</code>方法。
testString: assert(typeof bird.glide === "function");
- text: 你应该在<code>boat</code>上使用<code>glideMixin</code>,以提供<code>glide</code>方法。
testString: assert(typeof boat.glide === "function");
Challenge Seed
let bird = {
name: "Donald",
numLegs: 2
};
let boat = {
name: "Warrior",
type: "race-boat"
};
// Add your code below this line
Solution
let bird = {
name: "Donald",
numLegs: 2
};
let boat = {
name: "Warrior",
type: "race-boat"
};
function glideMixin (obj) {
obj.glide = () => 'Gliding!';
}
glideMixin(bird);
glideMixin(boat);