-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodulePattern.js
63 lines (49 loc) · 1.2 KB
/
modulePattern.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
60
61
62
/* _______________ encapsulation ________________ */
export const Encapsulation = (function () {
function foo(...args) {
this.count = 0;
const binding = (func) => {
return func.bind(this);
}
const addCount = binding(function (...argus) {
argus.length && argus.forEach(i => this.count += i);
})
const getCount = binding(function () {
return this.count;
})
args.length && addCount(...args)
return {
getCount,
addCount,
};
}
return foo;
})()
// let result = new Encapsulation(1, 2, 3, 9)
// console.log(result);
// console.log(result.getCount());
// result.addCount(1, 2, 3, 4, 5, 6)
// console.log(result.getCount());
/* --------------------------------------------- */
/* closure 闭包-模块模式 module pattern */
export const Counter = (function () {
var count = 0;
const changeCount = (num) => {
count += num;
return count;
}
return {
increment(num = 1) {
return changeCount(num)
},
decrement(num = -1) {
return changeCount(num)
},
getCount() {
return count;
}
}
})()
console.log(Counter.decrement());
console.log(Counter.increment());
console.log(Counter.getCount());