-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSingleton.js
59 lines (44 loc) · 1.21 KB
/
Singleton.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* Simple Singleton function
*
* But this function has a problem:
*
* It's possible to mutate the instance in Singleton.instance
*/
function Singleton() {
if (!Singleton.instance) {
Singleton.instance = this
}
return Singleton.instance
}
// Creating the first instance
const singleton = new Singleton()
// The instances are equal because the function returned the same instance as the created before
console.log(singleton === new Singleton()) // === true
// -----------------------------------------------------------------------------
// Using closure concept
function Singleton2() {
// Set the instance.
let instance = this
// Override the original implementation.
Singleton2 = function () {
return instance
}
}
const singleton2 = new Singleton2()
console.log(singleton2 === new Singleton2())
// -----------------------------------------------------------------------------
// Using the module pattern
let Singleton3
// IIFE - Immediately-Invoked Function Expression
;(function () {
let instance
Singleton3 = function () {
if (instance) {
return instance
}
instance = this
}
})()
const singleton3 = new Singleton3()
console.log(singleton3 === new Singleton3())