处理JavaScript中的可选参数


127

我有一个静态javascript函数,可以使用1、2或3个参数:

function getData(id, parameters, callback) //parameters (associative array) and callback (function) are optional

我知道我总是可以测试给定参数是否未定义,但是我怎么知道传递的是参数还是回调?

最好的方法是什么?


可以传递的示例:

1:

getData('offers');

2:

var array = new Array();
array['type']='lalal';
getData('offers',array);

3:

var foo = function (){...}
getData('offers',foo);

4:

getData('offers',array,foo);

2
您能举例说明可以传递什么吗?
詹姆斯·布莱克2009年

Answers:


163

您可以知道向函数传递了多少个参数,还可以检查第二个参数是否是一个函数:

function getData (id, parameters, callback) {
  if (arguments.length == 2) { // if only two arguments were supplied
    if (Object.prototype.toString.call(parameters) == "[object Function]") {
      callback = parameters; 
    }
  }
  //...
}

您还可以通过以下方式使用arguments对象:

function getData (/*id, parameters, callback*/) {
  var id = arguments[0], parameters, callback;

  if (arguments.length == 2) { // only two arguments supplied
    if (Object.prototype.toString.call(arguments[1]) == "[object Function]") {
      callback = arguments[1]; // if is a function, set as 'callback'
    } else {
      parameters = arguments[1]; // if not a function, set as 'parameters'
    }
  } else if (arguments.length == 3) { // three arguments supplied
      parameters = arguments[1];
      callback = arguments[2];
  }
  //...
}

如果您有兴趣,请参阅John Resig的这篇文章,该文章介绍了一种在JavaScript上模拟方法重载的技术。


为什么使用Object.prototype.toString.call(parameters)==“ [object Function]”而不是typeof(parameters)==='function'?它们之间有重要区别吗?PS您提到的文章似乎使用了后者
Tomer Cagan

@TomerCagan我认为这是一个偏好问题。在问题下,您对该主题有一些好的答案/评论。
Philiiiiiipp '16

75

嗯-这意味着您正在使用不正确顺序的参数来调用函数...我不建议这样做。

我建议改为将一个对象喂给您的函数,如下所示:

function getData( props ) {
    props = props || {};
    props.params = props.params || {};
    props.id = props.id || 1;
    props.callback = props.callback || function(){};
    alert( props.callback )
};

getData( {
    id: 3,
    callback: function(){ alert('hi'); }
} );

好处:

  • 您不必考虑参数顺序
  • 您不必进行类型检查
  • 定义默认值更容易,因为不需要类型检查
  • 少头痛。想象一下,如果添加了第四个参数,则必须每次都更新类型检查,如果第四个或连续的也是函数呢?

缺点:

  • 是时候重构代码了

如果您别无选择,则可以使用函数来检测对象是否确实是函数(请参见上一个示例)。

注意:这是检测功能的正确方法:

function isFunction(obj) {
    return Object.prototype.toString.call(obj) === "[object Function]";
}

isFunction( function(){} )

“由于某些ES错误,这种方法在99%的时间内都可以工作。” 你能解释更多吗?为什么会出错?
jd。

我添加了正确的代码来检测功能。我相信错误在这里:bugs.ecmascript.org/ticket/251
meder omuraliev 2009年

我强烈建议您只喂一个对象。如果不是,请使用CMS的方法。
meder omuraliev 09年

哦...该死...刚刚发表了同样的想法。
09年

1
另一个可能的缺点是缺乏智能。我认为这没什么大不了的,但应该注意。
Edyn


2

您应该检查接收到的参数的类型。也许您应该使用arguments数组,因为第二个参数有时可能是“参数”,有时可能是“回调”,并为参数命名可能会引起误解。


2

我知道这是一个很老的问题,但是我最近处理了这个问题。让我知道您对这种解决方案的看法。

我创建了一个实用程序,可让我强烈键入参数并使它们为可选。您基本上将功能包装在代理中。如果跳过参数,则它是undefined。如果您具有多个彼此相邻且类型相同的可选参数,则可能会很奇怪。(有一些选项可以传递函数而不是类型来进行自定义参数检查,以及为每个参数指定默认值。)

这是实现的样子:

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

为了清楚起见,这是怎么回事:

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 ... */

           }
         );
};

您可以在我的GitHub存储库中查看rangingArgs代理代码:

https://github.com/joelvh/Sysmo.js/blob/master/sysmo.js

这是实用程序功能,其中包含从存储库复制的一些注释:

/*
 ****** Overview ******
 * 
 * Strongly type a function's arguments to allow for any arguments to be optional.
 * 
 * Other resources:
 * http://ejohn.org/blog/javascript-method-overloading/
 * 
 ****** Example implementation ******
 * 
 * //all args are optional... will display overlay with default settings
 * var displayOverlay = function() {
 *   return Sysmo.optionalArgs(arguments, 
 *            String, [Number, false, 0], Function, 
 *            function(message, timeout, callback) {
 *              var overlay = new Overlay(message);
 *              overlay.timeout = timeout;
 *              overlay.display({onDisplayed: callback});
 *            });
 * }
 * 
 ****** Example function call ******
 * 
 * //the window.alert() function is the callback, message and timeout are not defined.
 * displayOverlay(alert);
 * 
 * //displays the overlay after 500 miliseconds, then alerts... message is not defined.
 * displayOverlay(500, alert);
 * 
 ****** Setup ******
 * 
 * arguments = the original arguments to the function defined in your javascript API.
 * config = describe the argument type
 *  - Class - specify the type (e.g. String, Number, Function, Array) 
 *  - [Class/function, boolean, default] - pass an array where the first value is a class or a function...
 *                                         The "boolean" indicates if the first value should be treated as a function.
 *                                         The "default" is an optional default value to use instead of undefined.
 * 
 */
arrangeArgs: function (/* arguments, config1 [, config2] , callback */) {
  //config format: [String, false, ''], [Number, false, 0], [Function, false, function(){}]
  //config doesn't need a default value.
  //config can also be classes instead of an array if not required and no default value.

  var configs = Sysmo.makeArray(arguments),
      values = Sysmo.makeArray(configs.shift()),
      callback = configs.pop(),
      args = [],
      done = function() {
        //add the proper number of arguments before adding remaining values
        if (!args.length) {
          args = Array(configs.length);
        }
        //fire callback with args and remaining values concatenated
        return callback.apply(null, args.concat(values));
      };

  //if there are not values to process, just fire callback
  if (!values.length) {
    return done();
  }

  //loop through configs to create more easily readable objects
  for (var i = 0; i < configs.length; i++) {

    var config = configs[i];

    //make sure there's a value
    if (values.length) {

      //type or validator function
      var fn = config[0] || config,
          //if config[1] is true, use fn as validator, 
          //otherwise create a validator from a closure to preserve fn for later use
          validate = (config[1]) ? fn : function(value) {
            return value.constructor === fn;
          };

      //see if arg value matches config
      if (validate(values[0])) {
        args.push(values.shift());
        continue;
      }
    }

    //add a default value if there is no value in the original args
    //or if the type didn't match
    args.push(config[2]);
  }

  return done();
}

2

我建议您使用ArgueJS

您可以通过以下方式键入函数:

function getData(){
  arguments = __({id: String, parameters: [Object], callback: [Function]})

  // and now access your arguments by arguments.id,
  //          arguments.parameters and arguments.callback
}

通过您的示例,我认为您希望id参数为字符串,对吗?现在,getData需要一个String id,并且接受可选的Object parametersFunction callback。您发布的所有用例将按预期工作。



1

您是说可以进行如下调用:getData(id,parameters); getData(id,回调)?

在这种情况下,您显然不能依靠位置,而必须依靠分析类型:getType(),然后在必要时再分析getTypeName()

检查所讨论的参数是数组还是函数。


0

我想你想在这里使用typeof():

function f(id, parameters, callback) {
  console.log(typeof(parameters)+" "+typeof(callback));
}

f("hi", {"a":"boo"}, f); //prints "object function"
f("hi", f, {"a":"boo"}); //prints "function object"

0

如果您的问题仅在于函数重载(您需要检查“ parameters”参数是否为“ parameters”而不是“ callback”),我建议您不要理会参数类型,并
使用方法。这个想法很简单-使用文字对象组合您的参数:

function getData(id, opt){
    var data = voodooMagic(id, opt.parameters);
    if (opt.callback!=undefined)
      opt.callback.call(data);
    return data;         
}

getData(5, {parameters: "1,2,3", callback: 
    function(){for (i=0;i<=1;i--)alert("FAIL!");}
});

0

我想这可能是一个自我解释的例子:

function clickOn(elem /*bubble, cancelable*/) {
    var bubble =     (arguments.length > 1)  ? arguments[1] : true;
    var cancelable = (arguments.length == 3) ? arguments[2] : true;

    var cle = document.createEvent("MouseEvent");
    cle.initEvent("click", bubble, cancelable);
    elem.dispatchEvent(cle);
}

-5

您可以覆盖该功能吗?这将不起作用:

function doSomething(id){}
function doSomething(id,parameters){}
function doSomething(id,parameters,callback){}

8
不,这行不通。您不会收到任何错误,但是Javascript将始终使用您定义的最新函数。
jd。

6
哇。我以为你疯了 我刚刚测试过。你是对的。我的世界对我来说只是改变了一点。我想我今天要看很多JavaScript,以确保生产中没有这样的东西。感谢您的评论。我给了你+1。
J.Hendrix
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.