多个参数与选项对象 [英] Multiple arguments vs. options object

查看:25
本文介绍了多个参数与选项对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建具有多个参数的 JavaScript 函数时,我总是面临这样的选择:传递参数列表与传递选项对象.

When creating a JavaScript function with multiple arguments, I am always confronted with this choice: pass a list of arguments vs. pass an options object.

例如,我正在编写一个将 nodeList 映射到数组的函数:

For example I am writing a function to map a nodeList to an array:

function map(nodeList, callback, thisObject, fromIndex, toIndex){
    ...
}

我可以改用这个:

function map(options){
    ...
}

其中 options 是一个对象:

where options is an object:

options={
    nodeList:...,
    callback:...,
    thisObject:...,
    fromIndex:...,
    toIndex:...
}

推荐哪种方式?是否有关于何时使用一种与另一种的指南?

Which one is the recommended way? Are there guidelines for when to use one vs. the other?

[更新] 似乎有一个支持 options 对象的共识,所以我想添加一条评论:我想在我的案例中使用参数列表的一个原因是行为一致使用内置于 array.map 方法的 JavaScript.

[Update] There seems to be a consensus in favor of the options object, so I'd like to add a comment: one reason why I was tempted to use the list of arguments in my case was to have a behavior consistent with the JavaScript built in array.map method.

推荐答案

像许多其他人一样,我通常更喜欢将 options object 传递给函数,而不是传递一长串参数,但是这真的取决于确切的上下文.

Like many of the others, I often prefer passing an options object to a function instead of passing a long list of parameters, but it really depends on the exact context.

我使用代码可读性作为试金石.

I use code readability as the litmus test.

例如,如果我有这个函数调用:

For instance, if I have this function call:

checkStringLength(inputStr, 10);

我认为代码的可读性很好,传递单个参数也很好.

I think that code is quite readable the way it is and passing individual parameters is just fine.

另一方面,有这样的调用函数:

On the other hand, there are functions with calls like this:

initiateTransferProtocol("http", false, 150, 90, null, true, 18);

除非您进行一些研究,否则完全无法阅读.另一方面,这段代码读起来很好:

Completely unreadable unless you do some research. On the other hand, this code reads well:

initiateTransferProtocol({
  "protocol": "http",
  "sync":      false,
  "delayBetweenRetries": 150,
  "randomVarianceBetweenRetries": 90,
  "retryCallback": null,
  "log": true,
  "maxRetries": 18
 });

它更像是一门艺术而不是一门科学,但如果我必须说出经验法则:

It is more of an art than a science, but if I had to name rules of thumb:

在以下情况下使用选项参数:

Use an options parameter if:

  • 您有四个以上的参数
  • 任何参数都是可选的
  • 您曾经不得不查找函数以找出它需要哪些参数
  • 如果有人试图在尖叫ARRRRRG!"的同时勒死你

这篇关于多个参数与选项对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆