我正在寻找另一种替换此句子的方法。 (counter.set =(值)=> count =值; counter.decrease =()=。count-) 我该怎么办??
function makeCounter() {
let count = 0;
function counter() {
return count++
}
// Issue --
counter.set = (value) => count = value;
counter.decrease = () => count--;
// End of issue --
return counter;
}
let counter = makeCounter();
alert( counter() ); // 0
alert( counter() ); // 1
counter.set(10); // set the new count
alert( counter() ); // 10
counter.decrease(); // decrease the count by 1
alert( counter() ); // 10 (instead of 11)
答案 0 :(得分:1)
您需要使用new关键字进行更改...也可以使用class
class makeCounter {
constructor(){
this.count = 0;
}
function counter() {
return count++
}
set(value){ this.count = value;}
decrease(){this.count-- ;}
}
let counter =new makeCounter();
alert( counter() ); // 0
alert( counter() ); // 1
counter.set(10); // set the new count
alert( counter() ); // 10
counter.decrease(); // decrease the count by 1
alert( counter() ); // 10 (instead of 11)
答案 1 :(得分:0)
您可以使用课程
class Counter {
constructor() {
this.count = 0;
}
set(value) {
this.count = value;
}
increase(value) {
this.count += (value || 1);
}
decrease(value) {
this.count -= (value || 1);
}
}
const counter = new Counter();
console.log(counter.count);
counter.increase();
console.log(counter.count);
counter.increase();
console.log(counter.count);
counter.increase(10);
console.log(counter.count);
counter.decrease();
console.log(counter.count);
counter.decrease(2);
console.log(counter.count);