Skip to content

Instantly share code, notes, and snippets.

@radum
Forked from ilfroloff/ClassA.js
Created October 28, 2019 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radum/3bf4f854ff7dbb09ad002d61ebb63e5c to your computer and use it in GitHub Desktop.
Save radum/3bf4f854ff7dbb09ad002d61ebb63e5c 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