Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

245
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda