简体   繁体   中英

How can I deal with optional parameters in JavaScript?

I would like a function 'get' that takes an id, an optional property parameter and a callback function. It would be used like so:

get(14297, 'name', function processName(name) {...});
get(14297, function processStudent(student) {...});

I have included one possible implementation below

function get(id, property, callback) {
    var item = ...;
    // property is callback
    if (!callback) property(item);
    // callback is callback
    else callback(item[property])
}

It feels a little bit weird because

property(item);

Is actually a callback function depending on the context. Is there a better way to do this?

You should switch the parameters. Try this

function get(id, callback, property)
{
    if(typeof property === "undefined")
        callback(item);
    else
        callback(item[property]);
}

This is the pattern used by jQuery:

function get(id, property, callback) {

    // if the 2nd parameter is a function, assume that
    // only two parameters were supplied
    if (typeof property === 'function') {
         callback = property;
         property = undefined;
    }

    ...
}

Effectively, if it sees unexpected parameter types it just shuffles their contents around until they match the alternative definition.

You can change the order of parameters, or test what the function is given to work out what they are. eg

function get(id, property, callback) {
  if (arguments.length == 2) {
    // second argument is callback
    callback = property;
    property = void 0;
  }
  ...
}

or

function get(id, property, callback) {
  if (typeof property == 'function') {
    // second argument is callback
    callback = property;
    property = void 0;
  }
  ...
}

and so on, but that type of overloading is not particularly liked.

The arguments object is immutable. But you can slice it in an array, pop the last argument and deal with the other arguments as you normally would, since you know the callback argument isn't in it anymore.

Here is a way to do this:

function get() {
    // Copy the `arguments` object in an array, since it's immutable
    var args = Array.prototype.slice.call( arguments, 1 ),

    // Pop the last argument of the arguments
        callback = args.pop();

    // Then deal with other arguments
    // For example, check for the existence of the second argument
    if ( args[1] ) {
    }

    // Then, you can call the callback function
    callback();
}

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