Reputation: 4879
I found different topics explain how to create a singleton, but none of them worked for me. This is an example taken from this post
export default class Credentials {
static myInstance = null;
_userID = "";
static getInstance() {
if (myInstance == null) {
myInstance = new Credentials();
}
return myInstance;
}
getUserID() {
return this._userID;
}
setUserID(id) {
this._userID = id;
}
}
when I call Credentials.getInstance()
I get a warning
Can't find variable myInstance
Upvotes: 1
Views: 4140
Reputation: 6280
This should be enough for any kind of single ton instance in JS.
Now, wherever you import this the same instance will be used. You can cross check by adding a date inside the class and accessing it at various places where you imported this.
import { SomeClass } from 'some-class'
let singletonInstance;
if (!singletonInstance) {
singletonInstance = new SomeClass();
// singletonInstance.time = new Date();
}
export default singletonInstance;
Then import it using
import singletonInstance from './above-code-file'
Upvotes: 0
Reputation: 9143
I think the most clean and easy solution would be the "ES6 singleton pattern" (not sure if there is an official name for this pattern).
You export the instance as default and everywhere you import it you get the same instance. This relies on the fact that module require is cached.
You would create your class and export the like so:
class Credentials {
constructor() {
this._userID = "";
}
get userID() {
return this._userID;
}
set userID(userID) {
this._userID = userID;
}
}
export default new Credentials();
Wherever you import it you get the same instance:
import credentials from './credentials';
Upvotes: 0
Reputation: 35501
JS has no implicit field lookup like statically-compiled languages. You need to lookup variables on the class explicitly:
class Credentials {
static myInstance = null;
static getInstance() {
if (Credentials.myInstance == null) {
Credentials.myInstance = new Credentials();
}
return Credentials.myInstance;
}
}
Be careful with this approach since it's not truly a singleton because JS doesn't have proper class encapsulation.
You could change the instance directly easily:
Credentials.myInstance = 'something else';
Proper singleton with encapsulation should be implemented via a closure:
const Credentials = (() => {
let myInstance = null;
return class Credentials {
static getInstance() {
if (myInstance == null) {
myInstance = new Credentials();
}
return myInstance;
}
}
})()
Upvotes: 2