2665. 计数器 II - 闭包

Smile_slime_47

Problem: 2665. 计数器 II

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
/**
* @param {integer} init
* @return { increment: Function, decrement: Function, reset: Function }
*/
var createCounter = function(init) {
return{
initialVal:init,
value:init,
increment: function () {
this.value++
return this.value
},
decrement: function (){
this.value--
return this.value
},
reset: function (){
this.value=this.initialVal
return this.value
}
}
};

/**
* const counter = createCounter(5)
* counter.increment(); // 6
* counter.reset(); // 5
* counter.decrement(); // 4
*/
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
/**
* @param {integer} init
* @return { increment: Function, decrement: Function, reset: Function }
*/
var createCounter = function (init) {
const ret = {
initialVal: init,
value: init,
increment: function () {
return ++this.value
},
decrement: function () {
return --this.value
},
reset: function () {
return this.value = this.initialVal
}
}
return ret;
};

/**
* const counter = createCounter(5)
* counter.increment(); // 6
* counter.reset(); // 5
* counter.decrement(); // 4
*/
Comments
On this page
2665. 计数器 II - 闭包