This closure code would work:
function setupSomeGlobals(){
var num = 666;
gPrintNumber = function() { // play with var assignment
console.log(num)
}
gIncreaseNumber = function() {
num++;
}
}
setupSomeGlobals();
gPrintNumber();
gIncreaseNumber();
gPrintNumber();
Yet, when I place the var
keyword in front of the functions within the code, it all seems to not work. Why is that? Is var
making these variable local only? Why would that matter?
function setupSomeGlobals(){
var num = 666;
var gPrintNumber = function() { // play with var assignment
console.log(num)
}
var gIncreaseNumber = function() {
num++;
}
}
setupSomeGlobals();
gPrintNumber(); // ReferenceError: gPrintNumber is not defined
gIncreaseNumber();
gPrintNumber();