Easily Overload JavaScript Functions with Optional Parameters

Overloaded

I just answered a Stack Overflow question from a couple years ago titled “Handling optional parameters in javascript” and figured I’d write about my solution here.

I’ll start by saying that the easiest way to handle optional parameters in javascript is to use an “options” object that allows a function to be called with as many or as few parameters (arguments) as you wish.

function displayOverlay(options) {
  if (options.alert) { 
    alert(options.message); 
  }
}

However, if you need to use individual parameters, i’ve created a utility that acts as a proxy and lets you strongly type values.  It looks like this:

function displayOverlay(/*message, timeout, callback*/) {
  return proxy(arguments, String, Number, Function,
    function(message, timeout, callback) {
      /* ... your code ... */
    });
};

I call my proxy arrangeArgs(). Here’s a clearer explanation of what’s going on:

function displayOverlay(/*message, timeout, callback*/) {
  //arrangeArgs is the proxy
  return arrangeArgs(
           //first pass in the original arguments
           arguments,
           //then pass in the type for each argument
           String,  Number,  Function,
           //lastly, pass in your function and the proxy will do the rest!
           function(message, timeout, callback) {

             //debug output of each argument to verify it's working
             console.log("message", message, "timeout", timeout, "callback", callback);

             /* ... your code ... */

           }
         );
};

I created the arrangeArgs() proxy to handle optional parameters for you.  It works nicely.  The code is in my Sysmo.js utility library on GitHub. Let me know what you think!

Share

Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *


× 4 = twenty

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType