The way to solve the singleton pattern in JS (TS actually) is looks like this (the best approach if you ask me):
export default class Singleton {
private static _instance: Selection
constructor() {
if (Selection._instance) {
return Singleton._instance
} else {
Singleton._instance = this
}
}
}
And then:
import Singleton from './Singleton.ts'
const singleton_1 = new Singleton()
const singleton_2 = new Singleton()
singleton_1 === singleton_2 // true
But in this scenario I have to create new variables every time I need that class.
I can achieve exactly the same the easier way:
class Singleton {
constructor() {
// some logic
}
}
export default new Singleton()
import Singleton from './Singleton.ts'
const wut = Singleton.field
Singleton.method('do something')
Am I getting something wrong or the first approach is a little bit excessive and complicated and the second one just do the same thing in more obvious way?
I understand that if I have static fields in my class, I couldn’t use it that way, but cases when you really need static fields are rare.