Javascript Function
Javascript function definitions,There are few different methods to define a function in javascript
Example
function Samsple1()
{
log('Hello Aruna');
}...
Javascript Function
Javascript function definitions
There are few different methods to define a function in javascriptExample
function Samsple1()
{
log('Hello Aruna');
}
{
log('Hello Aruna');
}
Example
var fun = function Samsple2()
{
log('Hello Aruna');
};
{
log('Hello Aruna');
};
Example
var ops = {
Add:function AddNumbers(n1,n2)
{
return n1+n2;
}
};
var x = ops.Add(3,5); //x =8
var y = ops.AddNumbers(3,5); //
Add:function AddNumbers(n1,n2)
{
return n1+n2;
}
};
var x = ops.Add(3,5); //x =8
var y = ops.AddNumbers(3,5); //
not valid
Encapsulation-in-JavaScript
Example
var x = 2000;
var fun = function Encas()
{
var y = 12;
return y;
};
var total = x+y; //
var total = x+Encas()//total is 2012
var fun = function Encas()
{
var y = 12;
return y;
};
var total = x+y; //
Invalid use of y
var total = x+Encas()//total is 2012
Functions in Functions
Example
function OuterFunction(n)
{
function InnerFunction()
{
return n*n;
}
return InnerFunction();
}
var x = OuterFunction(10);// x = 100
//InnerFunction can not call direcly
{
function InnerFunction()
{
return n*n;
}
return InnerFunction();
}
var x = OuterFunction(10);// x = 100
//InnerFunction can not call direcly
Immediate Functions
Example
(
function() {...}()
)
;or
(
function() {...}
)
();Module Pattern
Extended immediate functionExample
var fun = (function(){
var m=2000,c=0,d=10,y=2;
return {
GetHiddenYear:function()
{
return m+c+d+y;
}
}
}());
var x = fun.GetHiddenYear(); //x==2012;
var m=2000,c=0,d=10,y=2;
return {
GetHiddenYear:function()
{
return m+c+d+y;
}
}
}());
var x = fun.GetHiddenYear(); //x==2012;
Passing function as a parameter
Example
function Add(n1,n2)
{
return n1+n2;
}
function calc(n1,n2,processForCalc)
{
return processForCalc(n1,n2);
}
function executeMath()
{
log(calc(4,4,Add));//output 8
}
{
return n1+n2;
}
function calc(n1,n2,processForCalc)
{
return processForCalc(n1,n2);
}
function executeMath()
{
log(calc(4,4,Add));//output 8
}
0 comments:
Post a Comment