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
重用。 glideMixin
的mixin
,它定义了一个名为glide
的方法。然后使用glideMixin
让bird
和boat
都能够滑行。 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.");'
```