带有太多参数的函数。如何使用和调用对象字面量作为参数

Function with too many arguments. How to use and call object literals as parameters

我有一个将元素附加到页面的函数。这个函数在多个地方被调用,所以我为 classNames 设置了参数,因为样式是由 bootstrap 完成的。

由于我多次调用该函数,因此填写参数值可能会造成混淆并导致错误。

我想在适当的地方使用 object literal。我不确定该怎么做,也不知道如何调用这样的函数。

我的函数:

const my_func = (a, b, c, d, e, f, g = true) => {
$(a).append(`
<div class='${b}'>${f}</div>
<input class='${b}'> />
<button class='${c}'></button>
if(g) {
  .....
}
`);
}

为了组织您的函数 您可以简单地 destructure 您的输入参数和基本赋值 ,然后无论何时调用它,您都可以指定每对输入参数和它的值由冒号 (:).

但请记住,您应该始终将逻辑部分和字符串部分分开,以使内容清晰易读。

所以我只是稍微修改了您的代码并向其中传递了一些虚拟值。

const my_func = ({
  a,
  b,
  c,
  d,
  e,
  f,
  g = true
}) => {
  let html = `<div class='${b}'>${f}</div>
              <input class='${b}'/>
              <button class='${c}'>${d}</button>`;

  if (g) {
    html += '<div>g is true</div>'
  }

  $(a).append(html);
}

const container = $(".container");
my_func({a: container, b: "red", c: "bold", d: "submit", f: "this is a division", g: true}); //I didn't pass e parameter to it and simply skipped it.
.red {
  color: red;
}

.bold {
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container"></div>

const my_func = ({ a, b, c, d, e, f, g = true }) => {
  $(a).append(`<div class='${b}'>${f}</div>`);
  $(a).sppend(`<input class='${b}' />`);
  $(a).sppend(`<button class='${c}'></button>`);
  if (g) {
    // do something
  }
}

my_func({ a: '', b: '', c: '', d: '', e: '', f: '', g: true });

Destructuring 将提取您知道的所有属性供以后使用的变量使用。这也清楚地说明了您计划从对象参数中使用哪些属性,并允许指定默认值(这要困难得多,但在不解构的情况下是可能的)。

// this example clearly shows what options the function accepts,
// and describes the function behavior without having to read any of the function body
function findText(query, {caseInsensitive = true, fuzziness = 1, maxMatches}){…}

但你不必解构。如果您真的不关心从对象中准确指定您需要什么(假设您将对象传递给其他函数等),那么只需接受该对象作为函数参数并根据需要引用属性。

// this function accepts an object (`calendar'), but cares more about its
// role than its contents
function saveAppointment(title, date, calendar=getDefaultCalendar()){…}

有时这会更好,具体取决于意图。如果您的对象表示影响函数行为方式的函数选项,那么解构通常是最清晰的。但是如果对象是某种数据或丰富的对象(特别是如果对象有方法),那么您可能不会重构它。这取决于您是否希望对象更 "transparent" 或不透明 - 函数是否对对象内部感兴趣,或者它是否需要以更多 "tell, don't ask" 样式与对象协作。