Reputation: 19
I have a question about a closure in JS. Below is the given fonction:
function multiplicationParDeux() {
var chiffre = 10;
var fonction = function() { console.log(chiffre * multiplicateur); }
chiffre = chiffre * 2;
var multiplicateur = 10;
return fonction;
}
var maFonction = multiplicationParDeux();
maFonction(); //Output: 200
How comes that the output is 200? I declared my multiplicateur variable after the closure , how does the console.log(chiffre * multiplicateur);
part recognize the multiplicateur variable?
Upvotes: 1
Views: 63
Reputation: 14462
Your inner function - fonction
drags with itself a record of variables with their values from its lexical scope (referencing environment) when returned from its enclosing function - multiplicationParDeux
or executed outside of its own lexical scope.
When you are returning fonction
, you may imagine its closure as an object with the following properties, that serves as a binding for free variables inside of fonction
.
chiffre: 20,
multiplicateur: 10
And each time the fonction
is executed, it consults this closure if it contains bindings for its free variables (chiffre
and multiplicateur
), and since it does, the outcome is indeed 200.
Important note, you don't create the closure, JS engine does so it is not created at author-time (although you may deduce the contents of the closure just by inspecting the function's lexical scope) but when JS engine is executing your code and decides that the closure will be needed.
Upvotes: 0
Reputation: 138267
Closuring does not mean that the variables are copied, but rather that the function keeps a reference to the outer scopes variables.
Upvotes: 1