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

时间:2015-07-11 04:18:57

标签: javascript scope closures

我正在尝试使用以下函数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的预期功能,如果内部函数elapsed返回,则变量0将为stopwatch。内部函数increase递增变量elapsed。然后setInterval在延迟1秒后调用increase。最后,这次再次返回stopwatch,其中包含更新后的值1

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

如何根据我的理解修改此功能,以便elapsed递增,并关闭并保存该值,以便在我将makeStopwatch分配给变量stopwatch1并调用时stopwatch1返回更新后的值?

1 个答案:

答案 0 :(得分:3)

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()),它将控制自我们创建秒表后的秒数。