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

241
Vistas
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 Respuestas
Responde la pregunta

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 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