DEV Community

Randy Rivera
Randy Rivera

Posted on

Using a Mixin to Add Common Behavior Between Unrelated Objects

  • 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 and Airplane. They can both fly, but a Bird is not a type of Airplane 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!");
  }
};
Enter fullscreen mode Exit fullscreen mode
  • The flyMixin takes any object and gives it the fly method.
let bird = {
  name: "Donald",
  numLegs: 2
};

let plane = {
  model: "777",
  numPassengers: 524
};

flyMixin(bird);
flyMixin(plane);
Enter fullscreen mode Exit fullscreen mode
  • Here bird and plane are passed into flyMixin, which then assigns the fly function to each object. Now bird and plane can both fly:
bird.fly();
plane.fly();
Enter fullscreen mode Exit fullscreen mode
  • The console would display the string Flying, wooosh! twice, once for each .fly() call.

Top comments (0)