Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.