Using a Mixin to Add Common Behavior Between Unrelated Objects
Randy Rivera
Posted on June 12, 2021
- As you have seen, behavior is shared through inheritance. However, there are cases when inheritance is not the best solution. Inheritance does not work well for unrelated objects like
Bird
andAirplane
. They can both fly, but aBird
is not a type ofAirplane
and vice versa. - For unrelated objects, it's better to use mixins. A mixin allows other objects to use a collection of functions.
let flyMixin = function(obj) {
obj.fly = function() {
console.log("Flying, wooosh!");
}
};
- The
flyMixin
takes any object and gives it thefly
method.
let bird = {
name: "Donald",
numLegs: 2
};
let plane = {
model: "777",
numPassengers: 524
};
flyMixin(bird);
flyMixin(plane);
- Here
bird
andplane
are passed intoflyMixin
, which then assigns thefly
function to each object. Nowbird
andplane
can both fly:
bird.fly();
plane.fly();
- The console would display the string
Flying, wooosh!
twice, once for each.fly()
call.
💖 💪 🙅 🚩
Randy Rivera
Posted on June 12, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.