DEV Community

Randy Rivera
Randy Rivera

Posted on

Using an IIFE to Create a Module

  • An immediately invoked function expression (IIFE) is often used to group related functionality into a single object or module.
  • Ex:
let isCuteMixin = function(obj) {
  obj.isCute = function() {
    return true;
  };
};
let singMixin = function(obj) {
  obj.sing = function() {
    console.log("Singing to an awesome tune");
  };
};
Enter fullscreen mode Exit fullscreen mode
  • We can group these mixins into a module as follows:
let funModule = (function() {
  return {
    isCuteMixin: function(obj) {
      obj.isCute = function() {
        return true;
      };
    },
    singMixin: function(obj) {
      obj.sing = function() {
        console.log("Singing to an awesome tune");
      };
    }
  };
})();
Enter fullscreen mode Exit fullscreen mode
  • Note that you have an immediately invoked function expression (IIFE) that returns an object funModule. This returned object contains all of the mixin behaviors as properties of the object. The advantage of the module pattern is that all of the motion behaviors can be packaged into a single object that can then be used by other parts of your code.

Top comments (0)