Wednesday, August 22, 2012

JavaScript Functions - Part 3

Before going to dig more on the JavaScript functions below are the key concepts to novices.
  1. Function: function is a set of code which will be executed when ever is calling.
  2. Constructor: constructor is a function which is associated with the class. normally constructor name and class name will be the same. without a constructor we can't create an object
  3. Method: a method is a function which is associated with the class. It will work only after creating an instance (for a while don't consider the static methods). Objects may / may not have the properties and methods.
In the previous posts(part-1,part-2) I posted like “JavaScript functions are objects”, “functions can be assigned to variables and they can be passed as parameters”. 


so functions have some methods and properties associate with it. there are some important properties and methods which are most useful while writing scripts.

arguments Property
this property hold all declared parameters in an array like object . but it is accessed with in the declared function. it is very useful when you doesn't know how may parameters will get.

function myfun(param1,param2){
return arguments.length;
}
alert(myfun(1,2));//alerts 2
alert(myfun(1,2,3,4))//alerts 4
function sumValues(){
var total=0;
for(var i=0;i<arguments.length; i++){
total += arguments[i];
}
alert(total);
}
sumValues(1,2,3);

//sum values with n parameters
function sumValues(){
var total=0;
for(var i=0;i<arguments.length; i++){
total += arguments[i];
}
alert(total);
}

sumValues(1,2); // alerts 3
sumValues(1,2,3); // alerts 6

Constructor Property
JavaScript doesn't have any class structure like C#, Java, VB.Net. It is a prototype based language. Creating classes are not possible with the JavaScript (Until you are using a framework like EXTJS). We are only having objects, I am creating a simple named function below.

//adding 2 numbers
function sum(num1,num2){
return num1+num2;
}
//constructor property
alert(sum.constructor); //alerts function Function() {   [native code] }

Prototype Property
Every function in JavaScript hold a object called prototype. this property is help full to get the some OOP Features (which i will discuss in a separate topic) .


function sum(num1,num2){
return num1+num2;
}
alert(sum.prototype);//alerts [object Object]

arguments.