【问题标题】:Function with too many arguments. How to use and call object literals as parameters参数太多的函数。如何使用和调用对象字面量作为参数
【发布时间】:2020-10-02 18:29:27
【问题描述】:

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

由于我多次调用该函数,为参数填写值可能会让人感到困惑并容易出错。

我希望在适当的位置使用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) {
  .....
}
`);
}

【问题讨论】:

  • 这和你已经得到的很相似,除了函数声明是const my_func = ({a,b,c,d,e,f})=&gt; { /* ... */};,调用函数时你可以做my_func({a:aVal, b:bVal})等等。如果需要,也可以在函数声明中使用rest parameter
  • @David784,这不是让人很困惑,而且很长吗?
  • 使用对象而不是位置参数的主要好处是顺序无关紧要。
  • @GarrettMotzner,啊啊啊有道理!谢谢!

标签: javascript jquery function ecmascript-6 object-literal


【解决方案1】:

为了组织你的函数你可以简单地destructure你的输入参数和基本赋值,然后每当你调用它时,你可以用冒号(@ 987654322@).

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

所以我只是稍微修改了您的代码,并将一些虚拟值传递给它。

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>

【讨论】:

    【解决方案2】:
    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 });
    

    【讨论】:

      【解决方案3】:

      Destructuring 会将您知道需要的所有属性提取到变量中以供以后使用。这也清楚地表明您计划从 object 参数中使用哪些属性,并允许指定默认值(这要困难得多,但可能,无需解构)。

      // 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()){…}
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 2015-11-22
        • 2018-08-15
        相关资源
        最近更新 更多