Processing Javascript Function Arguments

It seems that the best way to handle arguments in javascript functions is to require the caller to pass an associative array:

example = function(options) {
  alert('option1: ' + options.a + ', option2: ' + options.b);
}

The arguments are now called and not needed in any particular order when calling this function:

example({'b':'hello option2', 'a':'hello option1'});

The only thing I don’t like is that I need all this additional code to deal with the required and default arguments, not to mention the absence of additional arguments, so that the caller knows that they called the function incorrectly:

example = function(options) {
var required_args = ['a', 'd'];
var default_args = {'b':'option2', 'c':'option3'};
var allowed_args = ['a', 'b', 'c', 'd'];
// check required args
// check allowed args
for (var arg in default_args) {
    if (typeof options[arg] == "undefined")
              options[arg] = default_args[arg];
  }
  alert('option1: ' + options.a + ', option2: ' + options.b);
}

Is there a standard way to handle this? I think I can create a function like:

deal_with_args(options, required_args, default_args, allowed_args)

And throw some kind of exception if required_args or allowed_args are violated ...

+3
3
  • ? , .
  • - ,
  • "" " " .

"" - - :

function myFunc(required_param, some_param, param_with_default) {
  // obviously this needs modifiction (ie use 'typeof' as you did) 
  // if you're dealing potentially 'falsey' values
  param_with_default = param_with_default || 'some default value';
  // same caution applies here
  if(!required_param) {
    // throw some exception here, or return an error code, or whatever
  }

  // function code
}
+3

?

alert('option1: ' + (options.a || default_args[a]) + ', option2: ' + (options.b || default_args[b]));

( )

+1

, javascript, .. , , , .

In these cases, I find it reasonable to have a hash of reasonable defaults ready, and then extend it with the passed object.

I think most people will do this using the extend method in their selection (Object.extend (obj1, obj2) in the prototype, jQuery.extend (obj1, obj2, ... objn), etc. Under the hood, these methods are just perform for in and copy properties.

0
source

Source: https://habr.com/ru/post/1766199/


All Articles