phi*_*zzy 6 javascript closures scope
我有以下功能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());
Run Code Online (Sandbox Code Playgroud)
当我console.log打电话给我时stopwatch1,stopwatch2我0每次都会回来.
据我了解的预期功能makeStopwatch的变量elapsed将0通过内部函数若返回stopwatch.内部函数increase递增变量elapsed.然后在延迟1秒后setInterval拨打电话increase.最后,stopwatch这次使用预期的更新值再次返回1.
但是,这并不因为里面工作makeStopwatch,内部stopwatch,increase和setInterval功能都在相互独立的范围?
如何根据我的理解修改它以使其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.
Run Code Online (Sandbox Code Playgroud)
因此,如果将上述所有代码放入控制台,然后console.log(stopwatch1())偶尔调用,它将 console.log 自我们创建秒表以来的秒数。
| 归档时间: |
|
| 查看次数: |
649 次 |
| 最近记录: |