调用嵌套函数 JavaScript

Calling a nested function JavaScript

我是 JavaScript 的新手。我有这段代码。我需要打印以下内容:

//counter() should return the next number.
//counter.set(value) should set the counter to value.
//counter.decrease() should decrease the counter by 1

function makeCounter() {
  let count = 0;

  function counter() {
    return count++;
  }

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

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

如何在外部调用3个嵌套函数?

您只需 return 您的 counter

function makeCounter() {
  let count = 0;

  function counter() {
    return count++;
  }

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

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

const myCounter = makeCounter();

console.log(myCounter()); // 0
console.log(myCounter()); // 1
console.log(myCounter.set(42)); // 42
console.log(myCounter()); // 42 (*see why next)
console.log(myCounter.decrease()); // 43 (*see why next)
console.log(myCounter()); // 42

  • 注意符号 count++ 因为它 returns count 然后加 1。如果你想加 1 然后 return [=13 的新值=],请写++count.