Javascript 回调和可选参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5135566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript callbacks and optional params
提问by rvk
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?
但这将回调函数分配给大小和重量,我该如何解决这个问题来做我想做的事?
采纳答案by Wayne
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. One option is to pass optional arguments in a single object.
JavaScript 参数必须在位置上与预期参数对齐,因此在传递的其他参数之间省略参数是行不通的。一种选择是在单个对象中传递可选参数。
// 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() {});
回答by Bergius
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 () { /* ... */ });
回答by SLaks
You can check arguments.lengthto 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'参数是否为回调。
Using this information, you can figure out what was passed in and re-assign the parameters as necessary.
使用此信息,您可以找出传入的内容并根据需要重新分配参数。
回答by pimvdb
You could check for the arguments' types: http://jsfiddle.net/wknVA/.
您可以检查参数的类型:http: //jsfiddle.net/wknVA/。
回答by RedSparr0w
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)
});
回答by zVictor
I recommend ArgueJSfor that!
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 undefinedby the desired types.
您还可以通过更改undefined所需的类型来检查参数的类型。
回答by Murali VP
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. Making two options that are optional of the same type asks for confusion.
除了 SLaks 答案之外,调用者并不总是可以假设他们可以发送他们想要的任何参数,记录参数是可选的函数是最好的方法,对于函数调用实现者,参数检查的类型和可选的分组args 到 arg 列表末尾是其他的。制作两个相同类型的可选选项会导致混淆。

