gpt4 book ai didi

javascript - 闭包期间变量存储在哪里?

转载 作者:行者123 更新时间:2023-11-30 16:56:19 26 4
gpt4 key购买 nike

好的,我知道在下面的代码中,当父函数 counter 返回一个带有名为 count 的方法的对象时,会创建一个闭包。但是有人可以澄清我是否正确理解控制流吗?计数器函数赋值给变量c后,方法第一次被c.count()调用,输出为1,以后每增加一次称为存储的 n 递增并返回新值。我知道这可以通过闭包的魔力实现,因此通过调用四次我每次都得到一个以 4 结尾的新值,而不是简单地四次得到 1。但是 n 在等待我再次调用 count 方法以增加最近创建的值时每次“闲逛”时保存的值在哪里? n 再次清零为 0 需要什么条件?如果我声明一个新变量并将函数 counter 分配给它?试图把我的头围绕在这一切上,我想到了这些问题。我不确定我要问的是令人讨厌的还是痛苦的-提前谢谢你。

function counter() {
var n = 0;
return {
count: function() { return ++n; },
};
}
var c = counter();
console.log(c.count()); // 1
console.log(c.count()); // 2
console.log(c.count()); // 3
console.log(c.count()); // 4

最佳答案

where is the value that n holds each time "hanging out" while it waits for me to call the count method again to increment the most recently created value?

变量n,当然是保存在内存中。它的行为就像在全局范围内一样,但在 counter 范围内。

What will it take for n to have a clean slate again as 0?

重置它。

我已经用自执行函数样式重写了您的示例,以使其更清晰。希望对您有所帮助。

var c = (function counter(){
var n = 0;
return {
count: function() { return ++n; },
//don't use keyword 'var', it will create a new variable instead of reseting n
reset: function() { n = 0},
};
})();
console.log(c.count()); // 1
console.log(c.count()); // 2
console.log(c.count()); // 3
console.log(c.count()); // 4
console.log(c.reset());
console.log(c.count()); // 1
console.log(c.count()); // 2
console.log(c.count()); // 3
console.log(c.count()); // 4

关于javascript - 闭包期间变量存储在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29673439/

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