Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
182
rated 0 times [  185] [ 3]  / answers: 1 / hits: 21645  / 14 Years ago, fri, february 4, 2011, 12:00:00

I've always passed arguments to a function like so:



setValue('foo','#bar')

function setValue(val,ele){
$(ele).val(val);
};


Forgive the silly example. But recently I have been working on a project that has some functions that take a lot of arguments. So I started passing the arguments through as an object (not sure if that's the correct way to put that), like so:



setValue({
val:'foo',
ele:'#bar'
});


And then in the function:



function setValue(options){

var value = options.val;
var element = options.ele;

$(element).val(value);

};


My question is, is there a better way to do that? Is it common practice (or okay) to call these 'options'? And do you typically need to 'unpack' (for lack of a better term) the options and set local vars inside the function? I have been doing it this way in case one of them was not defined.



I'm really looking to not create bad habits and write a bunch of code that is ugly. Any help is appreciated and + by me. Thanks.


More From » javascript

 Answers
2

I do the exact same thing, except I don't declare a new variable for each option inside the function.



I think options is a good name for it although I shorten it to opts.



I always have a default object within the function that specify default values for each available option, even if its simply null. I use jQuery, so I can just use $.extend to merge the defaults and user-specified options like this: var opts = $.extend({}, defaults, opts);


[#93909] Wednesday, February 2, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leighrheac

Total Points: 313
Total Questions: 92
Total Answers: 94

Location: Papua New Guinea
Member since Thu, May 7, 2020
4 Years ago
;