Monday, August 15, 2011

Function in Java script

Function in javascript:

DataType : Function is a datatype in javascript as other datatype like var,string and date.
e.g:
function checktype()
{}
alert(typeof(checktype));

As mentioned above function is datatype so we can assign function to variable, pass function as parameter to a function and can return as value.

Ex1:-
var funVal= function add(n1,n2)
{
return n1+n2;
}

funVal(8,19);

Ex2:-

function addValues(n1,n2)
{
return function(){
return n1+n2;
}
}

var retFnc= addValues(8,9);
retFnc();

Ex3:-

function addvalues(fns,fnr,n1,n2)
{
fns();
print(n1+n2);
fnr();
}
function fns(){
print("Execution start:");
}
function fnr()
{
print ("Execution end:");
}

addValues(fns,fnr,23,89);

Because function is datatype there are some methods associated with it:
1. call
2. apply

1) call takes 1or more than one parameter as calling parameters

function addValues(n1,n2)
{
return n1,n2;
}

addValues.call(null,5,6);

2) apply is different for call as if there is no of parameter is not fixed better approach is to use apply method.

function addValues()
{

for(var i=0;i
{
print(arguments[i].toString());
}

}

addValues.apply(null,[4,6,7]);
addValues.apply(null, [34,31,23,45]);

One more thing is associated with function that i would like to talk is context we are also able to use context inside javascript function.

Ex:-
var thisContext= { val=0;}


function addValue(n1)
{
return this.val+n1;
}

print(addValue.call(thisContext,n1));

is the way use controls in jQuery.

Ex:
$("#btnOk").click(function {
this.Value+="Clicked!!!!";
});

Happy Programming :)
Let knowledge flow like water!!!!!!!!!!!!!

No comments:

Post a Comment