JavaScript Scope: Closure
Closures provide a way to hold or trap an activation object in memory.
They can be used for defining private variables, and storing variables outside of a functions life-cycle.
JavaScript has function-level scope only, so unlike other C languages a ‘for’ or ‘if’ block won’t hold scope.
for (var homer in ['doh!','ray','mee']) {
// do something with homer
}
console.log(homer); // logs 'mee'
var homer = 'hmmmm donuts';
if(true){
var homer = 'doh!';
// other code
}
console.log(homer); // logs 'doh!'
To create scope within the if block we could do the following:
var homer = 'hmmmm donuts';
if(true){
(function(){
var homer = 'doh!';
// other code
}());
}
console.log(homer); // 'hmmmm donuts'
But generally it’s not good practice to reuse variable names for different purposes.
In the global scope, variables resolve to the global object ‘window’. ‘this’ in a global function will be the global object, but variables defined within that function wont resolve to the global object. Functions have there own activation object.
function(){
var homer = 'woo hoo';
var myobject = {
homer: 'spiderpig, spiderpig...',
say: function(){
console.log(homer);
console.log(this.homer);
}
}
myobject.say();
}
From this example we first log ‘woo hoo’ from current function scope then ‘spiderpig, spiderpig…’ as defined on the object.
Trackbacks