Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!