简体   繁体   中英

Javascript - Passing arguments to function

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.

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);

I believe this is a great pattern. I've heard an options object like this referred to as a "builder object" in other languages (at least in the context of object creation). Here are some of the advantages:

  • Users of your function don't have to worry about what order the parameters are in. This is especially helpful in cases like yours where the method takes a lot of arguments. It's easy to get those mixed up, and JavaScript will not complain!
  • It's easy to make certain parameters optional (this comes in handy when writing a plugin or utility).

There are some pitfalls though. Specifically, the user of your function could not specify some of the options and your code would choke (note that this could also happen with a normal JS function: the user still doesn't have to supply the correct arguments). A good way for handling this is to provide default values for parameters that are not required:

var value = options.val || 0;
var element = options.ele || {};  

$(element).val(value);

You could also return from the function immediately or throw an exception if the correct arguments aren't supplied.

A good resource for learning how to handle builder objects is to check out the source of things like jQueryUI .

I realize this question is a year old, but I think the cleanest way to pass an arbitrary number of arguments to a JavaScript function is using an array and the built in apply method:

fun.apply(object, [argsArray])

Where fun is the function, object is your scope/context in which you want the function to be executed and the argsArray is an array of the arguments (which can hold any number of arguments to be passed.

The current pitfall right now is that the arguments must be an array (literal or object) and not an array-like object such as {'arg' : 6, 'arg2' : "stuff"}. ECMAScript 5 will let you pass array-like objects, but it only seems to work in FireFox at the moment and not IE9 or Chrome.

If you look at the jQuery implementation, it uses an options class to handle most of the arbitrary-number-of-parameters functions, so I think you are in good company.

The other way is to test for arguments.length, but that only works if your arguments are always in the same order of optionality.

It's worth remembering that all functions have a bonus parameter called arguments that is an object very much like a JS array (it has length but none of the array functions) that contains all the parameters passed in.

Useful if you want to pass in a range of parameters (eg

function Sum() {
    var i, sum = 0;
    for (i=0; i < arguments.length; i++){
        sum+=arguments[i];
    }
    return sum;
};

If this isn't the case and you just have a lot of parameters, use the params object as you've described.

Nothing wrong with that practice.

"Options" seems like as good a name as any.

You don't need to "unpack" them, but if you'll be accessing the same item several times, it will be a little more efficient to reference them in local variables because local variable access is generally quicker than property lookups.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM