gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:29:29 26 4
gpt4 key购买 nike

我有以下功能 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电话 increase延迟 1 秒后。最后,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.

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

关于javascript - 如何使用javascript中的闭包访问函数内另一个范围内的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31353352/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com