Skip to content

Instantly share code, notes, and snippets.

@ilfroloff
Last active March 4, 2024 09:01
Show Gist options
  • Save ilfroloff/76fa55d041b6a1cd2dbe to your computer and use it in GitHub Desktop.
Save ilfroloff/76fa55d041b6a1cd2dbe to your computer and use it in GitHub Desktop.
JavaScript Singleton using class
'use strict';
import Singleton from 'Singleton';
class ClassA extends Singleton {
constructor() {
super();
}
singletonMethod1() {
// ...
}
singletonMethod2() {
// ...
}
// ...
}
console.log(
ClassA.instance === ClassA.instance,
ClassA.instance === new ClassA,
new ClassA === new ClassA
); // true, true, true
'use strict';
const singleton = Symbol('singleton');
export default class Singleton {
static get instance() {
if(!this[singleton]) {
this[singleton] = new this;
}
return this[singleton];
}
constructor() {
let Class = new.target; // or this.constructor
if(!Class[singleton]) {
Class[singleton] = this;
}
return Class[singleton];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment