loading...
Cover image for JavaScript Mixins

JavaScript Mixins

toddster79 profile image Todd Carlson ・2 min read

My tumble down the rabbit hole continues. This week I have been focusing on object oriented programming concepts in JavaScript. Having learned Ruby as my first language, I found that I was able to pick up and understand the JavaScript approach to OOP without too much difficulty. One such concept that I found to be especially useful were mixins.

So what are mixins exactly? Well, in a nutshell, a mixin is a class containing methods that can be used by other classes without a need to inherit from it. For example, if you are working with unrelated objects inheritance is probably not the best solution. Let's say you have a cheetah object, and a trackStar object. They both can run, but they are not the same species. So if you wanted both of these objects to be able to use the same run function, a mixin would serve you well. The reason for this is because mixins allow unrelated objects to use the same collection of functions.

let runMixin = function(obj) {
  obj.run = function() {
    console.log("Running fast!");
  }
};
Enter fullscreen mode Exit fullscreen mode

The runMixin takes in any object that you pass into it and gives it the run method.

let cheetah = {
  name: "Chester",
  topSpeed: "80 mph"
};

let trackStar = {
  name: "Steve Prefontaine",
  homeTown: "Coos Bay, OR"
};

runMixin(cheetah);
runMixin(trackStar);
Enter fullscreen mode Exit fullscreen mode

We pass in the cheetah object and the trackStar object. They both get assigned the run function. We can now call the run function on either unrelated object resulting in both objects now being able to run fast.

cheetah.run(); // prints "Running fast!"
trackStar.run(); // prints "Running fast!"
Enter fullscreen mode Exit fullscreen mode

So a mixin is basically a class that that contains methods for other classes to use.

I hope this post has shed some light on how to use mixins in JavaScript. OOP in JavaScript is a vast topic that I encourage you all to explore more deeply. The more I learn about JavaScript, the more I appreciate just how powerful it is.

Posted on by:

toddster79 profile

Todd Carlson

@toddster79

Full-Stack Web Developer

Discussion

pic
Editor guide