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