这是我的代码:
function makeCounter(x) {
x = x || 0;
var obj = {
value: x,
increment: function(){
x = x + 1;
return x;
},
decrement: function() {
x = x - 1;
return x;
}
}
return obj;
}
var counter = makeCounter();
console.log(counter.increment()); // output is 1
console.log(counter.value); // output is 0
Run Code Online (Sandbox Code Playgroud)
现在,我想知道如何编辑代码,以便在counter.increment()之后值为1.
您需要在增加或减少后更新值,并使用this.value而不是x变量.
function makeCounter(value = 0) {
return {
value,
increment () {
return ++this.value;
},
decrement () {
return --this.value;
}
};
}
let counter = makeCounter();
console.log(counter.increment()); // output is 1
console.log(counter.value); // output is 1Run Code Online (Sandbox Code Playgroud)