Tuesday, November 20, 2007

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

Monday, November 05, 2007

JavaScript function/procedure using Prototype.js framework

Prior to web2.0 and AJAX, I only use javascript for front end validation and some front end calculations.

When I started using Prototype.js, I learned a lot more about javaScript, particulary with functions/procedure.

If you are a java programmer, you probably write functions the traditional way.

e.g.
function sayHello() {
return "hello there!";
}

But there's an alternative. You can define functions this way:

var sayHello = function() {
return "hello there!";
}

Here we declared a global variable called sayHello, to which we have assigned a value. The value is, in this case, an anonymous function defined using the function() keyword.

Take note, that the effect of both ways are the same. (The second one is similar to C/C++ pointer to a function. wink-wink ).

In JavaScript, a Function is a first-class object that exists in its own right, unlike the method of an object in an object-oriented language.

To give an example about Function being a first-class object, let me explain about how to call the functions.

To call a function, you would use parenthesis.
e.g.

sayHello();

if you dont put the "()" it will return a reference to a function. You use that if you want to assign another name to call your function.

var sayHelloFxn = sayHello;

How does javascript function deal with input parameters? Consider this example

var animalCreator = function(species,color) {
return { species:species, color:color }
}


I created a function that returns a object (HashMap or associative array depending on how you want to call it ). What happened if I do call it like this?

1) var whale = animalCreator("mammal" );
2) var frog = animalCreator("amphibian", "green");
3) var eagle = animalCreator("bird", "white", "bald eagle" );

You would probably think that 1) and 3) will generate error. According to the declaration of the function "animalCreator" it accepts two arguments, called species and color. It is obviously designed to be called with two arguments, but in JavaScript (and unlike Java or C/C++/C#) this is nothing more than a guideline.

For 1), since there's only one argument, the second one will be set to null. and for 3) we pass a third argument. That will simply be ignored.

Okay, so much for function call. Let me explain about function as first-class object and how function changes its context. I know its weird, but the function object itself has its own function. You can use Function.call() or Function.apply() to execute a function.
e.g.

var food = { meal:"bread and egg", drink: "green tea" };
var person = {
meal:"bacon and rice",
drink: "coffee",
eat: function () {
return "I'd like to eat " + this.meal + " and drink " + this.drink;
}
};

1) person.eat();
2) person.eat.call(food);


Here we define 2 objects (food and person). Person has a function called "eat". The first one will return:

I'd like to eat bacon and rice and drink coffee.

while the second one, since you are using call, and passing an object as an argument. The function context will use the context of food. It will return:

I'd like to eat bread and egg and drink green tea.

As you noticed, the "this" changes context. This concept is very important in javaScript, because this is unlike java and C/C++/C#.

The apply() method operates similarly, except that it expects all arguments to the function invocation to be bundled as an array that is passed in as the second argument to apply(). Subsequent arguments are ignored.

Function Closures

What is function closures?

Friday, November 02, 2007

Free Directory Assistance?

If you need a phone number of a certain establishment you normally dial 411. It cost you about $1 (depending on your cellphone carrier).

411 is old school now. There's a way to get this information (and more) for free. Call 1-800-GOOG-411 or 1-800-466-4411, and you can ask not only for the numbers, but even for address, direction, etc. You can also request to deliver it to you via SMS (text message).

Kudos to Google!

Now what are you waiting for? Try it out! and save it in your phone's contact!

Check video below for more information.