Use an IIFE to Create a Moduleeee

what is the difference in openly declaring mixins and doing it through IIFE

Your code so far


let isCuteMixin = function(obj) {
  obj.isCute = function() {
    return true;
  };
};
let singMixin = function(obj) {
  obj.sing = function() {
    console.log("Singing to an awesome tune");
  };
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/object-oriented-programming/use-an-iife-to-create-a-module

The difference is that if you do not use an IIFE, the functions (or mixins as described on that page) are created in the global scope.

i.e. after you declare them, you can access them via:

window.isCuteMixin()

This is considered bad practice as you can run into issues with naming collisions, for example if you’re working in a team and someone else creates a function with the same name (isCuteMixin) - you’ll hear people refer to this as “polluting the global scope”.

Declaring them instead inside the IIFE means they are ONLY accessible from the object that was assigned the return value of the IIFE.

In that example, motionModule can now use the 2 functions, e.g. motionModule.glideMixin(), but if you tried window.glideMixin() you would get undefined because the functions were not created in the scope of window.

Does that make sense?

4 Likes

Oh, additionally it makes it much easier to work with your code, especially as your project gets bigger and bigger. Knowing that you can just go to motionModule for all your motion related functions, or userModule for all functions related to managing a user makes it much easier to maintain.

thanks for the explanation!

I was wondering the same question. Your explanation is super clear and easy to understand. Thank you!

1 Like