我正在尝试使用以下函数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
拨打stopwatch1
和stopwatch2
时,我每次都会收到0
。
据我了解makeStopwatch
的预期功能,如果内部函数elapsed
返回,则变量0
将为stopwatch
。内部函数increase
递增变量elapsed
。然后setInterval
在延迟1秒后调用increase
。最后,这次再次返回stopwatch
,其中包含更新后的值1
。
但这不起作用,因为在makeStopwatch
内,内部stopwatch
,increase
和setInterval
函数都在彼此的独立范围内?
如何根据我的理解修改此功能,以便elapsed
递增,并关闭并保存该值,以便在我将makeStopwatch
分配给变量stopwatch1
并调用时stopwatch1
返回更新后的值?
答案 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())
,它将控制自我们创建秒表后的秒数。