如何使用 javascript 中的闭包访问函数内另一个作用域中的变量?

How to access variables in another scope inside a function using closure in javascript?

我有以下函数 makeStopwatch,我正在尝试通过它来更好地理解 javascript 闭包:

var makeStopwatch = function() {
  var elapsed = 0;
  var stopwatch = function() {
    return elapsed;
  };
  var increase = function() {
    elapsed++;
  };

  setInterval(increase, 1000);
  return stopwatch;
};

var stopwatch1 = makeStopwatch();
var stopwatch2 = makeStopwatch();

console.log(stopwatch1());
console.log(stopwatch2());

当我 console.log 调用 stopwatch1stopwatch2 时,我每次都分别返回 0

据我了解 makeStopwatch 的预期功能,如果由内部函数 stopwatch 返回,变量 elapsed 将是 0。内部函数 increase 递增变量 elapsed。然后 setInterval 在延迟 1 秒后调用 increase。最后,这次再次返回 stopwatch,更新后的值预计为 1.

但这不起作用,因为在 makeStopwatch 内部,内部 stopwatchincreasesetInterval 函数都在彼此独立的范围内?

我如何修改它以按照我的理解工作,以便 elapsed 递增并关闭并保存该值,以便在我将 makeStopwatch 分配给变量 stopwatch1 时并调用 stopwatch1 返回更新值?

var makeStopwatch = function() {
  var elapsed = 0;

  // THIS stopwatch function is referenced later
  var stopwatch = function() {
    return elapsed;
  };

  var increase = function() {
    elapsed++;
  };
  // This setInterval will continue running and calling the increase function.
  // we do not maintain access to it.
  setInterval(increase, 1000);

  // THIS returns the stopwatch function reference earlier.  The only way
  // we can interact with the closure variables are through this function.
  return stopwatch;
};

var stopwatch1 = makeStopwatch();
// This runs the makeStopwatch function.  That function *RETURNS* the
// inner stopwatch function that I emphasized above.

console.log(stopwatch1());
// stopwatch1 is a reference to the inner stopwatch function.  We no longer
// have access to the elapsed variable or the function increase.  However
// the `setInterval` that is calling `increase` is still running.  So every
// 1000ms (1 second) we increment elapsed by 1.

因此,如果我们将上述所有代码放入控制台,然后偶尔调用 console.log(stopwatch1()),它将 console.log 自我们创建秒表以来的秒数。