为什么变量不会在关闭时重置(Javascript) [英] Why Don't Variables Reset in a Closure (Javascript)

查看:502
本文介绍了为什么变量不会在关闭时重置(Javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试了解闭包,但是一件事仍然困扰着我。如果我有以下代码:

I've been trying to learn about closures, but one thing still perplexes me. If I have the following code:

var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

add();
add();
add();

// Returns "3"

如果我调用add()三次,为什么不每次都将计数器设置为零,然后返回将计数器递增1的匿名功能?自调用功能运行后,它会跳过吗?抱歉,如果问题很简单,我很难理解。任何帮助将不胜感激。

If I call add() three times, why dosen't it set counter to zero every time, then return the anonymous funtion that increments counter by one? Does it skip over it once the self-invoking function runs? Sorry if the question seems simple, I'm having a hard time understanding it. Any help would be greatly appreciated.

推荐答案


如果我多次调用add(),为什么要剂量为是不是每次都将计数器设置为零,然后返回将计数器递增1的匿名功能?

If I call add() three times, why dosen't it set counter to zero every time, then return the anonymous funtion that increments counter by one?

因为 add 是该匿名函数,因为包含 counter 的函数被调用及其结果分配给 add

Because add is that anonymous function, because the function containing counter got called and its result was assigned to add:

var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();
//^^----------- calls the outer function, returns the anonymous inner function

如果您没有称呼它:

var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
});
//^--- no () here

...然后 add 会按照您所说的去做,每次您调用它时,都会返回一个带有自己计数器的新函数:

...then add would do what you said, it would return a new function with its own counter, each time you called it:

var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
});

var a = add();
var b = add();
var c = add();

console.log("a's first call:  " + a());
console.log("a's second call: " + a());
console.log("a's third call:  " + a());
console.log("b's first call:  " + b());
console.log("b's second call: " + b());
console.log("b's third call:  " + b());

console.log("a's fourth call: " + a());
console.log("b's fourth call: " + b());

.as-console-wrapper {
  max-height: 100% !important;
}

那不是重置 计数器,每次创建一个新的计数器。

That's not resetting counter, that's creating a new counter each time.

这篇关于为什么变量不会在关闭时重置(Javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆