Last active
August 3, 2022 15:54
-
-
Save mohammadhb/a9d52562fae63e722adea13c6e9d32eb to your computer and use it in GitHub Desktop.
Javascript ES6 Singleton pattern with pure class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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