T
T
taki1542016-12-26 08:16:14
JavaScript
taki154, 2016-12-26 08:16:14

Why does a javascript closure behave this way?

In one of the js screencasts, I saw an example, the performance of which does not fit in my head:
While I was formulating the question, I already reached the answer myself, but still I want to understand whether I came to the right result. :)

function foo(){ 
  var a = []; 

  for(var i=0; i<3; i++) {
    a.push(function(){console.log(i)})
  }

  return a; 

} 

var x = foo(); 

x[0](); 
x[1](); 
x[2]();

On each iteration in the foo function, we add the body of the anonymous function into the array "a" . At the time of its call, we refer to the current value of the variable i , which, after iterations of the loop, becomes equal to 3 .
There is a problem with the function call. It turns out that we have assigned the function call foo() to x , so by calling it through x[0]() , we work immediately with the value of the array a[0] of the foo() function . Tell me, please, did you understand everything correctly? Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alex maslakoff, 2016-12-26
@taki154

Everything is correct.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question