3.0 KiB
3.0 KiB
id, title, challengeType, videoUrl, localeTitle
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
587d7db2367417b2b2512b89 | Use a Mixin to Add Common Behavior Between Unrelated Objects | 1 | 使用Mixin在不相关的对象之间添加常见行为 |
Description
Bird
和Airplane
这样的无关对象,继承不起作用。它们都可以飞行,但是Bird
不是一种Airplane
,反之亦然。对于不相关的对象,最好使用mixins
。 mixin
允许其他对象使用一组函数。 让flyMixin = function(obj){
obj.fly = function(){
console.log(“Flying,wooosh!”);
}
};
flyMixin
接受任何对象并为其提供fly
方法。 让bird = {这里将
名称:“唐纳德”,
numLegs:2
};
让plane = {
型号:“777”,
numPassengers:524
};
flyMixin(鸟);
flyMixin(平面);
bird
和plane
传递给flyMixin
,然后将fly
函数分配给每个对象。现在bird
和plane
都可以飞行: bird.fly(); //打印“飞行,嗖!”注意
plane.fly(); //打印“飞行,嗖!”
mixin
如何允许相同的fly
方法被不相关的对象bird
和plane
重用。 Instructions
glideMixin
的mixin
,它定义了一个名为glide
的方法。然后使用glideMixin
让bird
和boat
都能够滑行。 Tests
tests:
- text: 您的代码应该声明一个<code>glideMixin</code>变量,它是一个函数。
testString: 'assert(typeof glideMixin === "function", "Your code should declare a <code>glideMixin</code> variable that is a function.");'
- text: 你的代码应该使用<code>bird</code>对象上的<code>glideMixin</code>来为它提供<code>glide</code>方法。
testString: 'assert(typeof bird.glide === "function", "Your code should use the <code>glideMixin</code> on the <code>bird</code> object to give it the <code>glide</code> method.");'
- text: 你的代码应该使用<code>boat</code>对象上的<code>glideMixin</code>来为它提供<code>glide</code>方法。
testString: 'assert(typeof boat.glide === "function", "Your code should use the <code>glideMixin</code> on the <code>boat</code> object to give it the <code>glide</code> method.");'
Challenge Seed
let bird = {
name: "Donald",
numLegs: 2
};
let boat = {
name: "Warrior",
type: "race-boat"
};
// Add your code below this line
Solution
// solution required