Wednesday, February 13, 2008

JavaScript Function Closure

Coming from a C++/JAVA background, it was hard for me to assimilate the concept of Function Closure in JavaScript. Now that I understand it, I'd like to share it here with you. Seriously, it's best explained by example than description. Here's an example.


var thingsToDo = {};

function initializeThingsToDo() {
var food= {
name: "Ramen",
type: "Tokatsu"
};
thingsToDo.eat = function() {
alert("I'm going to eat: " + food.name);
}
}

//Execute
initializeThingsToDo();
thingsToDo.eat();


Okay, what did I do here? First, I created an empty (global) Object called "thingsToDo", then I added a global function called "initializeThingsToDo". Inside this function I defined food object. I referenced the global object "thingsToDo" and attached a dynamic function called "eat" in the object.

After the code definitions, I ran the global function initializeThingsToDo, and called the method thingsToDo.eat().

I know you would say that this is crazy because when I ran thingsToDo.eat(), the method uses the food object but it's already out of scope.


//Execute
initializeThingsToDo();
thingsToDo.eat(); // When this is executed,
// the food object is already out of scope!


Na ah?! Not in JavaScript. You see, when you run the code, JavaScript will create a closure to the food object. After that, it saves it in the memory. The interpreter knows that it will be used for later. (It doesn't deallocate the food object in the memory. )

The power of function closure is well executed when you use AJAX. When you define your AJAX callback function, it gets called asynchronously. It creates a closure and call the objects/functions when it's ready.

If you are not familiar with JavaScript Object and Functions, you can read these links:

Java vs. JavaScript object
JavaScript usign Prototype.js
JavaScript Function

Source:
http://liminescence.blogspot.com/2007/11/javascript-function-closure.html

No comments: