Skip to content

Instantly share code, notes, and snippets.

@mohammadhzp
Created February 6, 2023 09:25
Show Gist options
  • Save mohammadhzp/960c8047e92b7da6c9cc22bf488a64ac to your computer and use it in GitHub Desktop.
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.
class Dummy extends Singleton {
constructor() {
super();
this.i = 0;
}
incr() { ++this.i; }
}
<!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>
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
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