Can I ensure a class exists only once and share that instance with other classes by explicitly passing it to each constructor (method 1) or by instantiating it once and exporting the variable (method 2)?
// foo.ts (the shared class)
class Foo {
// ...
}
Method 1:
// bar.ts (one of the classes using Foo)
class Bar {
constructor(foo: Foo) {
// ...
}
}
Method 2:
// a file containing the instantiation (how to name it?)
import {Foo} from './foo';
export const foo = new Foo();
// bar.ts
import {foo} from './theFileContainingTheInstantiation';
class Bar {
// use foo
}
While global variables are not recommended, I find method 2 much more efficient as it eliminates the need to add an argument to each class constructor and guarantees a unique instantiation without requiring careful handling in every class.