views:

130

answers:

1

I have a project that I am working on where I am not able to use jQuery. Since using jQuery, I have become very acustomed to the way that parameters can be set in a function. It is very nice doing it the "jQuery" way, so that it does not matter the order, or even if you use all defaults like a normal function method would need.

So, my question is how would I turn like this:

function myFunction(param1, param2, param3, param4, param5) {

}

To a jQuery like method, without using jQuery:

function myFunction({
 param1: 'test',
 param2: 'test2'
});

Any help on this would be great!

+3  A: 

I think you want to define a single options argument in your function, and extend it against a default values object:

function myFunction (options){
  options = extend({ // default values
    param1: 'test',
    param2: 'test2'
  }, options || {});

  alert(options.param1);
}

// helper function to "extend" the 'b' object from 'a'
// by copying its properties
function extend(a, b) {
  for ( var prop in b ) {
    a[prop] = b[prop];
  }
  return a;
}

Then if you call:

myFunction ({param1:'overriden!'});

options.param1 will be overriden within your function, and options.param2 will remain with its default value "test2".

CMS
+1 You wrote your answer faster and more succinctly than me. Good work
micmcg
Thank you @micmcg!
CMS
Yes! This was just what I was looking for!
Nic Hubbard