Javascript 回调和可选参数
如果我正在创建一个接受两个强制参数的函数,其中一个是回调,还有几个可选参数,我该如何对其进行编码,以便当我仅使用两个强制参数调用它时它就可以工作。
前任:
函数保存(颜色,大小,重量,回调){ ... }
其中颜色和回调是必需的,大小和重量是可选的。因此,如果有人想仅使用颜色和回调来调用此函数......
保存('蓝色', function(...) { ... }) { ... }
save('blue', 56, function(...) { ... }) { ... }
但这将回调函数分配给大小和重量,我该如何解决这个问题以执行我想要的操作?
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.
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', 56, function(...) { ... }) { ... }
But this assigns the callback function to size and weight, how can I fix this to do what I want?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
参数对象很好地解决了您的问题,如下所示:
像这样使用:
A parameter object solves your problem nicely, like so:
Use like this:
JavaScript 参数必须在位置上与预期参数对齐,因此在传递的其他参数之间遗漏参数是行不通的。一种选择是在单个对象中传递可选参数。
像这样传递它们:
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.
Pass them like this:
您可以检查
arguments.length
来查看传递了多少个参数,并检查typeof Weight === 'function'
来查看参数是否是回调。使用此信息,您可以弄清楚传入的内容并根据需要重新分配参数。
You can check
arguments.length
to see how many arguments were passed, and check whethertypeof weight === 'function'
to see whether an argument is a callback or not.Using this information, you can figure out what was passed in and re-assign the parameters as necessary.
您可以检查参数的类型:http://jsfiddle.net/wknVA/。
You could check for the arguments' types: http://jsfiddle.net/wknVA/.
首先,将回调默认值设置为其自身或下一个最接近的参数,直到可选参数的末尾(第一个),
接下来检查可选参数是否设置为函数(回调)或未定义,并将它们设置为默认值或将它们设置为自己。
及用法:
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.
And usage:
除了 SLAks 答案之外,调用者并不总是可以假设他们可以发送他们想要的任何参数,记录参数可选的函数是最好的方法,对于函数调用实现者、参数检查的类型和可选的分组args 到 arg 列表末尾的是其他。制作两个相同类型的可选选项会造成混乱。
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.
我推荐 ArgueJS !
您还可以通过将
undefined
更改为所需类型来检查参数的类型。I recommend ArgueJS for that!
You can also check the type of your arguments by changing
undefined
by the desired types.