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

156
Vistas
How to get separate "global" module per instance?

Is it possible get individual "global" module for each instance?

import MyModule from './index.js';

const first = new MyModule();
const second = new MyModule();

// PLEASE SEE EXAMPLE BELOW FOR LOGS

// expect to log for both:
// 1. "in entry: true"
// 2. "in init: true"

// but second module logs:
// 1. "in entry: false"
// 2. "in init: false"

Issue being here that both share globals and 1. instance changes property to false.

What are my options to have in individual globals module per instance?

PS! I have tens of thousands of lines of legacy code. Would be 100x better if I didn't need to change/remove/refactor globals.js contents nor these imports import globals from './globals.js';. Nevertheless, give all your ideas - I need to fix it, even if I need to change a lot.


Code for example above / minimal reproducible example

index.js

import globals from './globals.js';
import init from './init.js';

export default function MyModule (conf) {
  console.log('in entry:', globals.state1);

  init();
}

globals.js

export default {
  state1: true,
};

init.js

import globals from './globals.js';

export default function init () {
  console.log('in init:', globals.state1);
  globals.entry1 = false;
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Since an object is passed by reference you need to create a copy each time you use globals.

A good way is to export a function like:

/* globals.js */
const globals = { // Maybe wrap the object in Object.freeze() to prevent side effects
    state1: true,
};

export default () => ({ ...globals });

You can then call the function to create a copy each time you need it.

/* init.js */
import getGlobals from './globals.js';

export default function init () {
  const globals = getGlobals();
  console.log('in init:', globals.state1);
  globals.entry1 = false;
}
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