Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

236
Vistas
Why is IIFE required in the following context?

I am working to emulate the require functionality with a few javascript functions, for example:

// We set up an object that will include all the public modules
// And then a require function which basically just accesses that public module
const modules = {};
function require(moduleName) {
    return modules[moduleName];
}
modules['math.js'] = function() {
    // hidden implementation details
    let incr = x => ++x;
    return {
        incr, 
        sum(x,y) { return x+y; }
    }
}

Why is it required to do modules['math.js'] = (function() {...})(); and not just a normal non-invoked function call as above?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

modules["match.js"] is only a function. You probably want it to be an object:

modules["math.js"] = { ... };

But then you won't have private members or functions you can use! Everything will be public. So to solve this we create a closure:

modules["math.js"] = function () {
    let priv = 0;

    return { ... };
};

Here's where we are now. To make it a closure AND have modules["math.js"] be a nice object we can use, we immediately call this function:

modules["math.js"] = (function () {
    let priv = 0;

    return { ... };
})();

Now, modules["math.js"] is an object with members and methods we can use, AND it has a private locally scoped variable named priv that can be used only by the module.

This is similar to ES6 modules where you export a select few values bound to identifiers and everything else in the file is private.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda