简体   繁体   English

Javascript回调和可选参数

[英]Javascript callbacks and optional params

If I am creating a function that takes in two mandatory parameters, one is a call back, and a couple optional how can I code it so that when I call it with only the 2 mandatory parameters it works. 如果我正在创建一个带有两个必需参数的函数,一个是回调函数,还有几个可选参数,我可以如何对其进行编码,这样当我调用它时只有2个必需参数可以工作。

Ex: 例如:

function save(color, size, weight, callback) { ... } 功能保存(颜色,大小,重量,回调){...}

Where color and callback are mandatory and size and weight are optional. 颜色和回调是强制性的,尺寸和重量是可选的。 So if someone wants to call this function with only color and callback... 因此,如果有人想要仅使用颜色和回调来调用此函数...

save('blue', function(...) { ... }) { ... } save('blue',function(...){...}){...}

 save('blue', 56, function(...) { ... }) { ... }

But this assigns the callback function to size and weight, how can I fix this to do what I want? 但这会将回调函数分配给大小和重量,我该如何解决这个问题呢?

A parameter object solves your problem nicely, like so: 参数对象可以很好地解决您的问题,如下所示:

function save(params, callback) {
    params.color = params.color || 'default';
    params.size = params.size || 0;
    params.weight = params.weight || 0;

    // ...

    if (callback instanceof Function) { callback(); }
}

Use like this: 使用这样:

save({ color: 'blue', weight: 100 }, function () { /* ... */ });

JavaScript arguments must be aligned to the expected parameters positionally, so leaving out an argument in between others that are passed isn't going to work. JavaScript参数必须在位置上与预期参数对齐,因此在传递的其他参数之间省略参数是行不通的。 One option is to pass optional arguments in a single object. 一种选择是在单个对象中传递可选参数。

// callback is required
// additional arguments are passed as props of 'options'
function save(options, callback) { 
    var color = options.color || 'blue';
    var size = options.size || 72;
}

Pass them like this: 像这样传递给他们:

save({ color: 'red' }, function() {});

You can check arguments.length to see how many arguments were passed, and check whether typeof weight === 'function' to see whether an argument is a callback or not. 您可以检查arguments.length以查看传递了多少个参数,并检查typeof weight === 'function'是否typeof weight === 'function'以查看参数是否为回调。

Using this information, you can figure out what was passed in and re-assign the parameters as necessary. 使用此信息,您可以确定传入的内容并根据需要重新分配参数。

To start with you set the callback default to itself or the next closest param until the end(first) of the optional params, 首先,将回调默认设置为自身或下一个最接近的参数,直到可选参数的结束(第一个),

next you check if the optional params are set as functions (the callback) or undefined and set them to there defaults or set them to themselves. 接下来检查可选参数是否设置为函数(回调)或未定义,并将它们设置为默认值或将它们设置为自己。

function optional_params(color, size, weight, callback){
    // set callback to itself or the next optional paramater until you have checked all optional paramaters
  callback = callback || weight || size;
    // check if weight is a function(the callback) or undefined and if so set to a default value, otherwise set weight as weight
  weight = typeof weight != 'function' && typeof weight != 'undefined' ? weight : "1.2kg";
    // do the same as above with weight
  size = typeof size != 'function' && typeof size != 'undefined' ? size : "L";
    // invoke callback
  callback(color,size,weight);
}

And usage: 用法:

optional_params("Red",function(color,size,weight){
  console.log("color: " + color); // color: Red
  console.log("size: " + size); // size: L //(default)
  console.log("weight: " + weight); // weight: 1.2kg //(default)
});

您可以检查参数的类型: http//jsfiddle.net/wknVA/

I recommend ArgueJS for that! 我推荐ArgueJS

function save() {
  arguments = __({color: undefined, size: [undefined], weight: [undefined], callback: Function})

  // access your args by arguments.paramName. Ex.:
  // alert(arguments.color)
...
}

You can also check the type of your arguments by changing undefined by the desired types. 您还可以通过更改所需类型的undefined来检查参数的类型。

In addition to SLaks answer, it is not always possible for the caller to assume they can send whatever args they want, documenting the function which args are optional is the best way, for the function call implementor, type of arg check and grouping of optional args to the end of the arg list are others. 除了SLaks的答案之外,调用者并不总是可以假设他们可以发送他们想要的任何args,记录args是可选的函数是最好的方法,对于函数调用实现者,arg检查的类型和可选的分组arg列表末尾的args是其他的。 Making two options that are optional of the same type asks for confusion. 制作两个可选的相同类型的选项会产生混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM