为什么多次调用时,闭包函数中的javascript变量不会重置为默认值? [英] Why do javascript variables in closure functions not reset to a default when called multiple times?

查看:506
本文介绍了为什么多次调用时,闭包函数中的javascript变量不会重置为默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,有人可以向我解释为什么多次调用计数器会导致值 i 每次调用都会增加?

In the code below please can someone explain to me why multiple calls to counter result in the value of i increasing each time it is called?

我的理解是,因为我们在<$中专门设置 i = 0; c $ c> makeCounter ,每次 makeCounter 都是通过计数器变量调用的, i 应该重置为0.我不明白为什么不是这种情况。

My understanding is that as we specifically set i = 0; in makeCounter, each time makeCounter is called through the counter variable, i should be reset to 0. I cannot understand why this is not the case.

function makeCounter() {
  // `i` is only accessible inside `makeCounter`.
  var i = 0;

  return function() {
    console.log( ++i );
  };
}

// Note that `counter` and `counter2` each have their own scoped `i`.

var counter = makeCounter();
counter(); // logs: 1
counter(); // logs: 2


推荐答案


每次通过计数器变量调用makeCounter

each time makeCounter is called through the "counter" variable

这是错误的。

您只需拨打 makeCounter() 一次– at var counter = makeCounter();

counter 是对返回函数,关闭 i 变量。

You're only calling makeCounter() once – at var counter = makeCounter();.
counter is a reference to the returned function, which closes over the i variable.

调用 counter()将执行此返回的函数,就像任何其他函数一样。

Calling counter() will execute this returned function, just like any other function.

如果你写<$>你会期望的行为会发生c $ c> makeCounter()()多次。

这篇关于为什么多次调用时,闭包函数中的javascript变量不会重置为默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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