-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleton.js
More file actions
57 lines (50 loc) · 1.1 KB
/
singleton.js
File metadata and controls
57 lines (50 loc) · 1.1 KB
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
/*
An object that exists in a single instance
*/
// WITH GLOBAL VARIABLE
var instance;
class Counter {
constructor() {
if (!instance) instance = this;
instance.count = 0;
return instance;
}
getCount() {
return instance.count;
}
increaseCount() {
return instance.count++;
}
}
var testCount1 = new Counter();
var testCount2 = new Counter();
testCount1.increaseCount();
testCount1.increaseCount();
testCount1.increaseCount();
console.log('testCount2 is', testCount2);
// LINK ON STATIC OPTION IN CLASS CONSTRUCTOR
class superCounter {
constructor() {
if (typeof Counter.instance === 'object') {
return Counter.instance;
}
this.count = 0;
Counter.instance = this;
return this;
}
getCounter() {
return this.count;
}
increaseCount() {
return this.count++;
}
}
var superTestCount1 = new superCounter();
var superTestCount2 = new superCounter();
var superTestCount3 = new superCounter();
superTestCount1.increaseCount();
superTestCount1.increaseCount();
superTestCount2.increaseCount();
superTestCount3.increaseCount();
superTestCount1.increaseCount();
console.log(superTestCount1);