Andrew Heins

default-image

Intro to Mixins (in Javascript)


based off microevent.js by jeromeetienne
https://github.com/jeromeetienne/microevent.js/blob/master/microevent.js

I was just reading through microevent.js by jeromeetienne and stumbled across the awesomeness that are Javascript mixins! I’ve use his code as a template to show how mixins work in Javascript.

 

Hey! Just let me see the darn demo!

 

And to those of you who stuck with me…

What is a mixin and why would I use it?

Mixins are a means of implementing inheritance. They’re cool because instead of inheriting from a class ahead of time, you can add functionality to an object on the fly, and can do it to many different objects.

Mixins are kind of like a utility belt. I don’t normally have batarangs, a grappling hook and smoke bombs, because I’m not a superhero, but if I suddenly need them, even though I’m made not of the right stuff, I can throw on the utility belt, and suddenly I’ve got ‘em :)

How do I use a mixin?

First we create our functionality template

var UtilityBelt=function(){};

and add the appropriate functions

UtilityBelt.prototype={
  batarang:function(){
    alert("Batarang! Thwippa thwippa thippa thwack!");
  },
  grapplingHook:function(){
    alert("Grappling Hook! Whizzzzzzzzzzz ka-Chink!");
  },
  smokeBomb:function(){
    alert("Smoke Bomb! Goodbye! Poof!");
  }
};

Next we create our little mixin function

UtilityBelt.mixin=function(obj){
  var things=["batarang","grapplingHook","smokeBomb"];
  for(var i=0;i<things.length;i++){
    obj.prototype[things[i]]=UtilityBelt.prototype[things[i]];
  }
};

Now we create our “Joe Average” – decidedly not a superhero.

var Andrew=function(){};

Have him put on the utility belt…

UtilityBelt.mixin(Andrew);

And suddenly his thinks he’s BATMAN!!

Andrew.prototype.batarang();
Andrew.prototype.grapplingHook();
Andrew.prototype.smokeBomb();

Seems pretty cool to me. As always, if you’ve got any questions or comments, you can leave a comment below, or catch me on Twitter.


Join the Conversation!