我不明白`value`来自哪里,以及'set`是什么

时间:2018-05-24 17:18:57

标签: javascript function javascript-objects

任务是:

  

修改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)

Source of the code

1 个答案:

答案 0 :(得分:2)

嗯,这是arrow functionvalue是该函数的第一个参数的名称。

counter.set = value => count = value;
counter.decrease = () => {
  count--;
  return counter;
}

上面的代码在ES5语法中转换为:

counter.set = function (value) {
  return count = value;
};
counter.decrease = function () {
  count--;
  return counter;
};