Functions with Objects as Parameters

by Mohan 2012-09-20 22:29:04


Organize and Improve Functions with Objects as Parameters
A very common use of objects in modern web development is to use them as parameters of a function. It is always difficult to remember the order of the parameters of a function; however, using an object is very useful because then we do not have to be concerned about the order of the parameters. Moreover, it is more organized in order to understand what we are doing. This method allows for you to organize and improve the functions with objects as parameters. For example:
function insertData(name,lastName,phone,address){
code here;
}
Could be remade like this:
function insertData(parameters){
var name = parameters.name;
var lastName = parameters.lastName;
var phone = parameters.phone;
var address = parameters.address;
}
It also is very useful at the time to have defaults values. Example:
function insertData(parameters){
var name = parameters.name;
var lastName = parameters.lastName;
var phone = parameters.phone;
var address = parameters.address;
var status = parameters.status || 'single' //If status is not defined as a property in the object the variable status take single as value
}
To use the function now is pretty simple; we could send the data in two ways:
//Example 1
insertData({name:âMikeâ, lastName:âRogersâ, phone:â555-555-5555â,address:âthe addressâ, status:âmarriedâ});


//Example 2
var myData = { name:âMikeâ,
lastName:âRogersâ,
phone:â555-555-5555â,
address:âthe addressâ,
status:âmarriedâ
};

insertData(myData);




599
like
0
dislike
0
mail
flag

You must LOGIN to add comments