Skip to content

Instantly share code, notes, and snippets.

@mohammadhb
Last active August 3, 2022 15:54
Show Gist options
  • Save mohammadhb/a9d52562fae63e722adea13c6e9d32eb to your computer and use it in GitHub Desktop.
Save mohammadhb/a9d52562fae63e722adea13c6e9d32eb to your computer and use it in GitHub Desktop.
Javascript ES6 Singleton pattern with pure class
class Counter {
static instance;
static getInstance(){
if(!Counter.instance) Counter.instance = new Counter();
return Counter.instance;
}
counter = 0;
getCount() {
return this.counter;
}
increment() {
this.counter = this.counter + 1;
return this.counter;
}
}
module.exports = Counter.getInstance();
//Works with new
class Counter {
static instance;
constructor(x){
this.x = x
if(!Counter.instance) Counter.instance = this;
return Counter.instance;
}
counter = 0;
getCount() {
return this.counter;
}
increment() {
this.counter = this.counter + 1;
return this.counter;
}
}
module.exports = Counter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment