功能属性示例说明

时间:2017-11-17 13:59:53

标签: javascript

我正在阅读一个JS教程,并且遇到了这个例子:

function makeCounter() {
  function counter() {
    return counter.count++;
  };
  counter.count = 0;

  return counter;
}

let counter = makeCounter();
counter.count = 10;
console.log(counter()) // logs 10

我不明白为什么它没有记录11而不是10?如果我们将count属性设置为10并存储了增加function counter属性的count,为什么属性不会增加到11?

3 个答案:

答案 0 :(得分:3)

您很好地理解了函数属性。这与++的工作方式有关。

return counter.count++;将返回counter.count当前值,然后递增,而不是相反。

答案 1 :(得分:0)

因为您正在使用 postfix 增加运算符,它首先返回其当前值,然后增加它。您可以将其更改为前缀增加:

   return ++counter.count;

答案 2 :(得分:-1)

您的函数makeCounter正在返回一个可以访问[[scope]]的函数。它正在使用closure。所以很明显它就是这样的。

关闭:'当一个函数从'。

中记忆来自他被调用的地方的数据

进一步资料; What is a 'Closure'?