* feat(tools): add seed/solution restore script * chore(curriculum): remove empty sections' markers * chore(curriculum): add seed + solution to Chinese * chore: remove old formatter * fix: update getChallenges parse translated challenges separately, without reference to the source * chore(curriculum): add dashedName to English * chore(curriculum): add dashedName to Chinese * refactor: remove unused challenge property 'name' * fix: relax dashedName requirement * fix: stray tag Remove stray `pre` tag from challenge file. Signed-off-by: nhcarrigan <nhcarrigan@gmail.com> Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
2.2 KiB
2.2 KiB
id, title, challengeType, forumTopicId, dashedName
id | title | challengeType | forumTopicId | dashedName |
---|---|---|---|---|
587d7db2367417b2b2512b89 | 使用 Mixin 在不相关对象之间添加共同行为 | 1 | 301331 | use-a-mixin-to-add-common-behavior-between-unrelated-objects |
--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)的能力。
--hints--
你应该声明一个变量名为glideMixin
的函数。
assert(typeof glideMixin === 'function');
你应该在bird
上使用glideMixin
,以提供glide
方法。
assert(typeof bird.glide === 'function');
你应该在boat
上使用glideMixin
,以提供glide
方法。
assert(typeof boat.glide === 'function');
--seed--
--seed-contents--
let bird = {
name: "Donald",
numLegs: 2
};
let boat = {
name: "Warrior",
type: "race-boat"
};
// Only change code below this line
--solutions--
let bird = {
name: "Donald",
numLegs: 2
};
let boat = {
name: "Warrior",
type: "race-boat"
};
function glideMixin (obj) {
obj.glide = () => 'Gliding!';
}
glideMixin(bird);
glideMixin(boat);