Tuesday, December 28, 2010

Functions

In Javascript functions are nothing but Objects. Only difference btw Objects and functions are, function can be called for execution, where as objects cannot. Since they are object they can have there own properties and methods. 

In Javascript function can be defined in four ways. 

1. function declaration:
function boo(){}
these kind of function can be defined in global scope or inside other functions

2. function expression:
var boo=function(){};
When you don't give a name to function it's called anonymous function. Name property of such functions will have empty string ("") in Firefox, Webkit and will be undefined in IE.
3. named function expression:
var boo = function boo(){};
Naming a function expression is important when you wish to get function names to debug your code in debuggers like Firebug etc. And it's also important when you wish to call the function recursively within that.
4. by calling function constructor:
var boo = new Function ('a','b','return a+b');
This way of defining function is as bad as eval(). It needs extra care in escaping quotes. It's better to avoid it.

No comments:

Post a Comment