Using jQuery to Facilitate Default JavaScript Function Arguments

Posted by Mike on October 13, 2008

I’m not a very good JavaScript programmer, but today I decided to try and become a little bit better. My usual JavaScript methods involve a lot of hackery. One of the things I have never found a good solution for is passing arguments to a function. With the help of jQuery, today I found what I think to be a pretty good solution.

The technique is pretty simple: pass an options object to the function you’re calling (or don’t), create a default arguments object at the top of your function in question, and use jQuery’s extend function to merge the two.

Here’s some code to help explain:

/*
 * call the function with some options
 *
 * will alert:
 * option1: whatup
 * option2: false
 * option3: 2
 * option1: "andhow"
 */
mySweetFunction({
   option1: "whatup",
   option2: false,
   option3: 2
});
 
/*
 * call the function without any options
 *
 * will alert:
 * option1: sillystring
 * option2: true
 * option3: 100
 * option1: "andhow"
 */
mySweetFunction();
 
// the function in question
function mySweetFunction(options) {
   // establish the default values
   var args = {
      option1: "sillystring",
      option2: true,
      option3: 100,
      option4: "andhow"
   };
 
   // use jQuery's extend function to merge
   // args and options, modifying args.
   $.extend(args, options);
 
   alert("option1: " + args.option1);
   alert("option2: " + args.option2);
   alert("option3: " + args.option3);
   alert("option4: " + args.option4);
}
Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

Comments