tags:

views:

52

answers:

6

I have a typical javascript function with some parameters

my_function = function(content, options) { action }

if I call the function as such :

my_function (options)

the argument "options" is passed as "content"

how do i go around this so I can either have both arguments passed or just one ? thank you

+2  A: 

Like this:

my_function (null, options) // for options only
my_function (content) // for content only
my_function (content, options) // for both
Sarfraz
A: 

You will get the un passed argument value as undefined. But in your case you have to pass at least null value in the first argument.

Or you have to change the method definition like

my_function = function(options, content) { action }
Multiplexer
+4  A: 
my_function = function(hash) { use hash.options and hash.content };

and then call:

my_function ({ options: options });
my_function ({ options: options, content: content });
Darin Dimitrov
what is hash actually?
Muneer
Why do you call it "hash"?
Tim Büthe
@Muneer: It is just an example.
Sarfraz
A: 

Call like this

my_function ("", options);
Muneer
+2  A: 

You have to figure out as which argument you want to treat a single argument. You cannot treat it as content and options.

I see two possibilities:

  1. Either change the order of your arguments, i.e. function(options, content)
  2. Check whether options is defined:

    function(content, options) {
        if(options === undefined) {
            options = content;
            content = null;
        }
        //action
    }
    

    But then you have to document properly, what happens if you only pass one argument to the function, as this is not immediately clear by looking at the signature.

Felix Kling
A: 

Or you also can differentiate by what type of content you got. Options used to be an object the content is used to be a string, so you could say:

if ( typeof content === "object" ) {
  options = content;
  content = null;
}

Or if you are confused with renaming, you can use the arguments array which can be more straightforward:

if ( arguments.length === 1 ) {
  options = arguments[0];
  content = null;
}
galambalazs