(IIFE) is often used to group related functionality into a single object or module. For example, an earlier challenge defined two 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
Sorry, but this is not an answer for the question.
The function in your answer returns an object.
My question was why not to use an object from the start.
The important point here is that you don’t want to pollute the global namespace by adding variables to it. If you create an object, you have to name it. In this way you don’t have to name anything, not the function, not the object, the module just consists of a return value (the unnamed object) that can be imported directly by another program.
Sorry I didn’t see the challenge you were referring to, yes in this particular case, the return value will get stored in the global execution contexts which defeats the purpose. However, in a real module example, IIFE are not assigned to a variable in the module, the module is simply the IIFE which gets executed immediately when someone tries to require it/import it and gives it the object.
I have never wrote a module before, so I am asking just to understand when I might need an IIFE.
I have read that with ES6 modules the problem with global namespaces does not exist any more. Does it mean that IIFE for modules are outdated?