IIFE para crear Módulos

Cuéntanos qué está pasando:

¿Alguien sabe por qué se usan las IIFE para retornar un objeto con Mixins en lugar de asignar directamente el objeto con los Mixins a una variable para crear un módulo?

Mi código hasta el momento


// Con IIFE

/*
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");;
    }
  }
};
})();
*/

// Sin IIFE

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

Información de mi navegador:

El agente de usuario es: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36

Desafío: Utiliza una IIFE para crear un módulo

Enlaza al desafío:

Not really with the example code but using an IIFE does provide some benefits.

You can control what you return out, you might have internal data and methods you do not want to expose on an object. You can also pass in data using the IIFEs function call.

Look at The Module Pattern and Module Pattern Variations from the book Learning JavaScript Design Patterns.

1 Like