Why we "Use an IIFE to Create a Module" rather than direc object?

Hi,

In Use an IIFE to Create a Module section I could not quite understand we use IIFE for this purpose. Would that be possible to use direct object instead?

What are the differences between below two? Import & Export??

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");
    };
  }
  }
})();
let test = {
  isCuteMixin: function(obj) {
    obj.isCute = function() {
      return true;
    };
  },
  singMixin: function(obj) {
    obj.sing = function() {
      console.log("Singing to an awesome tune");
    };
  }
};

Modular programming is when you split a program up into independent parts. Each of those parts is a module. Each module has an API through which you interact with it.

An object is just a collection of properties, it’s not a module. In this trivial example, sure, could just use an object. But, for example, what if you want something me other stuff to happen before the return in the module, internal to it? What if it needed to do some setup before the return? How do you prevent people accessing the internal parts? How do you prevent people overwriting the internals by accident? etc etc.

JS has modules natively now, but it is still useful/informative to implement them yourself. As an example with actual module, say you created a file called fun.js

export function isCuteMixin (obj) {
  obj.isCute = function() {
    return true;
  }
}

export function singMixin (obj) {
  obj.sing = function() {
    console.log("Singing to an awesome tune");
  };
}

Thank you very much for detailed info. I agree. I was confused due to simplicity of the example.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.