Skip to content

JavaScript Scope: Closure

10 July, 2011

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.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: