I am trying to implement Singleton in JavaScript where I use Node.js module.export and require()
.
My issue is that module.export so far for me returns new object from a class.
If I make it so that all classes are only available requiring them from Singleton class and not require()
- then would I guarantee that I will have one instance only?
Because if all Other classes import from Singleton - how should I import Singleton?
In php no matter how many instances of Singleton you have - each share static properties. So if you make the instance static then all Singleton's no matter in which files they are invoked have the same memory and perform the same action.
However I have no idea what is the case with JavaScript
I also have another approach - If I make let instance
variable at the start of the file and check if its empty at the end and if it isn't I make another instance instance = new MyClass()
and then module.export = instance
. Would this give me the same result?
For example what I currently do
class MyClass {
//some logic here
}
module.export = new MyClass()
What I think of doing but no idea if it is good or it will work
if(!instance){
let instance = 1;
}
class MyClass {
//some logic here
}
if(instance === 1){
instance = new MyClass()
}
module.export = instance
Also to make matter more complicated I have seen several versions of implementations
Here -> https://www.sitepoint.com/javascript-design-patterns-singleton/
There are 3 examples -
1.Old JS ECMA 2015 way with functions
2.ECMA 2016 with object literal instead of class
3.With classes but again Object.freeze and const
Now..these versions make use of Object.freeze which I am not familiar with and const variables...which I am also not perfectly sure how they work.
To recap (TL;DR) - What I want to do is a way so that if I require a class in 10 files with require("MyClass")
I won't get 10 instances but only 1.
Does my way work properly and are the examples in the link with Object.freeze()
and the use of const
good working examples?Do I need an anctual Singleton class to do the job? Because solutions so far don't include one. And If I need - how do I pass that Singleton around so it has only one instance?
}module. exports = Singleton; As we can see we actually created two classes PrivateSingleton and Singleton . This is a trick to hide (create pseudo-private) constructor in Singleton class.
The ES6 Way — modulesES6 Modules are singletons. Thus all you have to do is define your object in a module. To test, you can try: const phrase = `${Math.
Node. js modules can behave like Singletons, but they are not guaranteed to be always singleton.
Node.js modules are singletons by default.
All imports referring to the same file would refer to the same object in memory. You don't have to do anything special
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With