freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../object-oriented-programming/use-a-mixin-to-add-common-b...

3.0 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7db2367417b2b2512b89 Use a Mixin to Add Common Behavior Between Unrelated Objects 1 使用Mixin在不相关的对象之间添加常见行为

Description

如您所见,行为通过继承来共享。但是,有些情况下继承不是最佳解决方案。对于像BirdAirplane这样的无关对象,继承不起作用。它们都可以飞行,但是Bird不是一种Airplane ,反之亦然。对于不相关的对象,最好使用mixinsmixin允许其他对象使用一组函数。
让flyMixin = functionobj{
obj.fly = function{
console.log“Flyingwooosh;
}
};
flyMixin接受任何对象并为其提供fly方法。
让bird = {
名称:“唐纳德”,
numLegs2
};

让plane = {
型号“777”
numPassengers524
};

flyMixin;
flyMixin平面;
这里将birdplane传递给flyMixin ,然后将fly函数分配给每个对象。现在birdplane都可以飞行:
bird.fly; //打印“飞行,嗖!”
plane.fly; //打印“飞行,嗖!”
注意mixin如何允许相同的fly方法被不相关的对象birdplane重用。

Instructions

创建一个名为glideMixinmixin ,它定义了一个名为glide的方法。然后使用glideMixinbirdboat都能够滑行。

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