Why do javascript variables in closure functions not reset to a default when called multiple times?

风流意气都作罢 提交于 2019-12-06 05:05:48

问题


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?

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

回答1:


each time makeCounter is called through the "counter" variable

That is wrong.

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

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

The behavior you're expecting would happen if you write makeCounter()() multiple times.




回答2:


each time makeCounter is called […] i should be reset to 0

That's right.

makeCounter is called through the counter variable

No it's not. The anonymous function returned by makeCounter is called with counter(). makeCounter was only called once, its result was assigned to the counter variable.

Note that counter and counter2 each have their own scoped i

That would be the case, yes. However your example is incomplete:

var counter = makeCounter();
counter(); // logs 1
var counter2 = makeCounter();
counter2(); // logs 1 again!
counter(); // still logs 2
counter2(); // logs 2


来源:https://stackoverflow.com/questions/17406875/why-do-javascript-variables-in-closure-functions-not-reset-to-a-default-when-cal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!