Here you need to use the first principles. Javascript uses lexical reach. This means that the scope of the execution context is determined by how the code is defined (lexical).
I would say that defining the Bar function is what causes the closure to create, because msg is "closed" in the function.
The actual creation of the closure occurs at run time (which is somewhat a tautological statement, since nothing happens in the computer program before it starts), because to determine the msg value in Bar when Bar is executed, the interpreter must know the value of the variable when Foo executed, and so on the chain.
I will give two answers to your question. The pedantic answer: none of the functions in itself is a closure. This is the definition of variables within functions in combination with the context of the execution of functions when they are launched, which defines the closure. General answer: any function that closes above a variable is a closure (Bar in your case).
Consider the problem everyone faces when using Javascript.
function A(x) { var y = x, fs = []; for (var i = 0; i < 3; i++) { fs.push(function(){ console.log (i + " " + x); }) } fs.forEach(function(g){g()}) } A('hi')
Most people would say that this would print "hi 1" followed by "hi 2" and then "hi 3". However, he produces "hi 3" 3 times. If only the definition of the function to be added to the array, using the variables defined in the external function, created a closure, how can this be?
This is because you need an execution context to define a closure that is not executed before execution. When executing functions in the array i has a value of 3 . The forEach statement has this execution context, so the output always uses 3.
source share