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

243
Visualizações
When we export new Foo() in JavaScript, by what rule do we know it is a singleton? (if we use webpack)

I often see code

export default Foo;

and Foo can be a function or a class, but if we do

export default new Foo();

I was told that it should be a singleton when multiple files in the project all do

import Foo from './Foo';

and it will be the same exact object, meaning that it'd be a singleton, but by what rule do we know it is instantiated once instead of instantiated multiple times?

I think the standard answer is that there is no guarantee, but what if we use webpack (or some other tool), can we know it is guaranteed to be only one?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

export default new Foo();

is same as:

const foo = new Foo();
export default foo;

As the module runs, 1 instance of Foo is created. That instance is being exported, so everyone who import it gets the same instance.

If you want to check that they are exactly the same, write 2 modules which import foo then have 1 of these modules pass its foo to the other via a function and do a comparison via === operator.

<html>
    <head>
        <script type="module" src="foo.js"></script>
        <script type="module" src="mod1.js"></script>
        <script type="module" src="mod2.js"></script>
    </head>
    <body></body>
</html>

foo.js:

export default {};

mod1.js:

import myFoo from './foo.js';

export function mod1Func(other_foo) {
   console.log('same?', other_foo === myFoo);
}

mod2.js:

import myFoo from './foo.js';
import { mod1Func } from './mod1.js';

mod1Func(myFoo);

And it should print:

same? true
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