Created
February 6, 2023 09:25
-
-
Save mohammadhzp/960c8047e92b7da6c9cc22bf488a64ac to your computer and use it in GitHub Desktop.
Singleton Impl in Javascript. `singleton.js` is the file you really need. the rest is there to make a running exmaple.
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 Dummy extends Singleton { | |
constructor() { | |
super(); | |
this.i = 0; | |
} | |
incr() { ++this.i; } | |
} |
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Example demonstrating Singleton in JS</title> | |
</head> | |
<body> | |
<h2>Checkout console</h2> | |
<script src="singleton.js"></script> | |
<script src="dummy.js"></script> | |
<script src="main.js"></script> | |
</body> | |
</html> |
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
Dummy.instance().incr(); | |
Dummy.instance().incr(); | |
let obj = Dummy.instance(); | |
obj.incr(); | |
console.log((Dummy.instance()).i); // 3 | |
console.log(obj.i); // 3 | |
console.log((Dummy.instance()) === obj); // true |
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 Singleton { | |
static _instance = null; | |
static instance() { | |
if (this._instance === null) { | |
this._instance = new this(); | |
} | |
return this._instance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment