I'm referencing this link about closures: https://stackoverflow.com/questions/111102/how-do-javascript-closures-work
This is specifically about javascript. In the second answer with 956 votes, The author returns the nested function "sayAlert" after assigning it to the var keyword as shown below. (Example 3)
function say667() {
// Local variable that ends up within closure
var num = 666;
var sayAlert = function() { alert(num); }
num++;
return sayAlert;
}
var sayNumber = say667();
sayNumber(); // alerts 667
However in the next example (Example 4), the author assigns the following functions, "gAlertNumber", "gIncreaseNumber", and "gSetNumber", without the var keyword. Then the author is able to call the nested functions as follows.
function setupSomeGlobals() {
// Local variable that ends up within closure
var num = 666;
// Store some references to functions as global variables
gAlertNumber = function() { alert(num); }
gIncreaseNumber = function() { num++; }
gSetNumber = function(x) { num = x; }
}
setupSomeGlobals();
gIncreaseNumber();
gAlertNumber(); // 667
gSetNumber(5);
gAlertNumber(); // 5
var oldAlert = gAlertNumber;
setupSomeGlobals();
gAlertNumber(); // 666
oldAlert() // 5
I tried adding the keyword var to the begging of each nested function, but in my console it returns an error. So I'm assuming there's a difference between the two. But I don't know what this tactic is called and why it works...