Function Declarations
function functionname(args1, args2,....argsn){
//code goes here;
}
Declared functions are not executed immediately.They will executed only when invoking in the later code.
Function Expressions
A Javascript function can also be defined using an expression.
var myVar = function(arg1, arg2) {return arg1 * arg2; }
The above function is stored in a variable and hence the variable can be used as a function call.
var myresult = myVar(9, 9); // returns 81.
These type of functions are anonymous function( a function without name).
Functions stored in a variables do not need function names. They always invoked using the variable name.
Function as Constructor
var myConstructorFun = new Function("a", "b", "return a* b" );
var myvar = myConstructorFun(9, 9);
Function Declarations Are Hoisted
Function declarations are hoisted—moved in their entirety to the beginning of the current
scope. That allows you to refer to functions that are declared later:
function foo() {
bar(); // OK, bar is hoisted
function bar() {
...
}
}
Note that while var declarations are also hoisted (see “Variables Are Hoisted” on page
23), assignments performed by them are not:
function foo() {
bar(); // Not OK, bar is still undefined
var bar = function () {
// ...
};
}
Functions defined as expressions are not hoisted.
Self Invoking Functions
Function expression can be made self invokable.
A self invoking expression is invoked automatically without being called.
Function expression will execute automatically if the expression is followed by ().
You can not a self invoke a function declaration.
You have to add parenthesis around the function to indicate that this is function expression.
(function (){
var myvar = "Hey" // I m self invokable
}) ();
This function is self invoking anonymous function.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.