I'm doing some experimenting with closures in Javascript, and with AngularJS directives (1.x) in particular.
To put it simply, I am wondering why ScenarioOne correctly captures the variable message
that we want, while ScenarioTwo does not. Why does the IIFE not capture and maintain the desired value of message
when it invokes itself?
SCENARIO ONE
// WORKS. Displays 'We want this message'
var message = 'We want this message';
element.bind('click', (function(){
var msg = message; // <-- MAGIC ?
return function(){
element.append('<p>Value of message: ' + msg + '</p>');
};
})());
message = 'We DON\'T want this message';
SCENARIO TWO
// DOES NOT WORK. Displays 'We DON'T want this message'
var message = 'We want this message';
element.bind('click', (function(){
return function(){
element.append('<p>Value of message: ' + message + '</p>');
};
})());
message = 'We DON\'T want this message';
I would like to understand, what are the magic mechanics (see line denoted <-- MAGIC ) of that assignment? What is the general rule about this? Do all variables that you want from an outer scope need to explicitly assigned to a new variable inside the IIFE?
Here is a working Plunkr of all this: https://plnkr.co/edit/1M9yrzuOi0bzNHxbb5rO