gpt4 book ai didi

javascript - 理解闭包

转载 作者:行者123 更新时间:2023-11-30 16:27:00 25 4
gpt4 key购买 nike

<分区>

我正在浏览高级 JavaScript 文本并遇到这些代码,我认为作者试图演示闭包但没有解释代码。我已经盯着这些代码集看了好几个小时,但仍然无法弄清楚为什么它们会产生不同的输出。

for (var i = 0; i <= 2000; i += 1000) {
setTimeout(function () {
console.log('i value in closure is ' + i);
}, i);
}
//Output
// i value in closure is 2000
// i value in closure is 2000
// i value in closure is 2000`

for (var i = 0; i <= 2000; i += 1000) { 
(function (i) {
setTimeout(function () {
console.log('i value in closure is ' + i);
}, i);
})(i);
}
//Output
// i value in closure is 0
// i value in closure is 1000
// i value in closure is 2000`

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