【问题标题】:Function property example explanation [duplicate]函数属性示例说明 [重复]
【发布时间】:2018-05-01 07:55:27
【问题描述】:

我正在阅读一个 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 并存储了递增count 属性的function counter,为什么该属性没有递增到11?

【问题讨论】:

标签: javascript


【解决方案1】:

你很了解函数属性。这与++ 的工作方式有关。

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

【讨论】:

  • 非常感谢,没想到这么简单。
【解决方案2】:

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

   return ++counter.count;

【讨论】:

    【解决方案3】:

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

    Closure : '当一个函数从他被调用的地方记住数据时'。

    更多信息; What is a 'Closure'?

    【讨论】:

    • 我认为您错过了实际问题。
    猜你喜欢
    • 2014-10-28
    • 1970-01-01
    • 2023-03-08
    • 2018-08-08
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多