bradxr
8/5/2018 - 11:29 PM

Use an IIFE to Create a Module

IIFE is often used to group related functionality into a single object or module

// mixins
function glideMixin(obj) {
  obj.glide = function() {
    console.log("Gliding on the water");
  };
}
function flyMixin(obj) {
  obj.fly = function() {
    console.log("Flying, wooosh!");
  };
}


// we can group these mixins into a module as follows
let motionModule = (function () {
  return {
    glideMixin: function (obj) {
      obj.glide = function() {
        console.log("Gliding on the water");
      };
    },
    flyMixin: function(obj) {
      obj.fly = function() {
        console.log("Flying, wooosh!");
      };
    }
  }
}) (); // The two parentheses cause the function to be immediately invoked


// demo
motionModule.glideMixin(duck);
duck.glide();