如何解决我不知道还有其他办法吗? Java脚本
我正在寻找另一种替换此句子的方法。 (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)
解决方法
您需要使用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)
,
您可以使用课程
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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。