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

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

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