DEV Community

loading...

Using an IIFE to Create a Module

Randy Rivera
Once I truly put my mind on something, I won't ever stop.
・1 min read
  • 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.

Discussion (0)