任务是:
修改
makeCounter()
的代码,以便计数器也可以减少并设置数字。
我不明白value
来自哪里,set
是什么。
function makeCounter() {
let count = 0;
function counter() {
return count++
}
// Here is this `value`. I understand what it does. But what is it,
// and where did it come from. How can I use it in general?
counter.set = value => count = value;
counter.decrease = () => count--;
return counter;
}
let counter = makeCounter();
alert(counter()); // 0
alert(counter()); // 1
// Also here, what kind of `set` is this?
// I’ve seen one in `Map.prototype.set()`, but there is no `Map` here.
counter.set(10); // set the new count
alert(counter()); // 10
counter.decrease(); // decrease the count by 1
alert(counter()); // 10 (instead of 11)
答案 0 :(得分:2)
嗯,这是arrow function,value
是该函数的第一个参数的名称。
counter.set = value => count = value;
counter.decrease = () => {
count--;
return counter;
}
上面的代码在ES5语法中转换为:
counter.set = function (value) {
return count = value;
};
counter.decrease = function () {
count--;
return counter;
};