Sunday, October 4, 2009

Javascipt Basics - Part 2

I did one blogpost couple of months back regarding Javascript Basics. This is continuation of that post.

A)EncodeUri and EncodeUriComponent -
These are builtin function which are used to encode the parameters.

EncodeUri(uri)-- will encode the part of the Url after the "http://somehostName/{This part will be encoded}

EncodeUrlComponent(url) -- it assumes that you will passing only the parameter that you want to encode. It will encode whatever you pass to the function.

For eg: if you pass

var url = 'http://yashwant.dns.mycompany.com/H ome';
alert(encodeURI(url));
Output:http://yashwant.dns.mycompany.com/H%20ome%3C/defau%20lt.aspx%3E

alert(encodeURIComponent(url));
Output:http%3A%2F%2Fyashwant.dns.mycompany.com%2FH%20ome%3C%2Fdefau%20lt.aspx%3E

B) Functions as Data
Javascripts treats functions as Data. So a function can be assigned to a varaible.
for eg:
var x = function()
{
alert('this is a function');
}
This notation is called as function literal notation

C) Anonymous Functions
Anonymous function are declared in place and dont have a name. Main use of Anonymous functions are it makes the code more elegant. They are used a lot as callback functions. As we know that Functions can be treated as data, so we can pass a function to another function as a parameter in javascript.
For eg:

var y = function (functionParameter)
{
alert('I am in functionA');
//CallBack the anonymous function that you passedin
functionParameter();
}
y(function() { alert('I am the callback function')});

D) Global Objects

When we declare a varaible using the object literal notation i.e

var Person = {
firstName: 'Yashwant',
middleName: 'Jaywant',
lastName: 'Patil',
print: function() //This is a method
{
alert(this.firstName + " " + this.middleName + " " + this.lastName);
}
}

Person property gets attached to the global javascript variable. In this case, since the code is running in a browser "person" property gets attached to the WINDOW object. So you can call the print method on the Person object like this

//Person Varaible gets attached as a property of the Global Object i.e Window object
window['Person'].print();

E)Configuration Objects
The rule I follow while writing javascript functions is :If there are more than 3 parameters that need to be passed to a javascript function, it is better to pass it as a JSON configuration object.

for eg:

//Cofiguration Objects...
var func = function Print(configurationObj)
{
for (var j in configurationObj)
{
alert(configurationObj[j]);
}
}
var obj = {"firstName":"Yashwant",
"middleName":"Jaywant",
"lastName": "Patil"
};
Print(obj);

It makes the code easire to read and understand.

Thanks,
Yash