具有必需值和空对象的参数对象解析

时间:2017-01-22 14:01:36

标签: javascript object parameters required destructuring

使用ES6参数对象解构,我们可以要求存在某些属性,并提供default valuesDr. Axel RauschmayerSix nifty ES6 tricks article中表示参数默认值仅在实际使用时进行评估。

下一个例子将提供更多关于我不理解的内容:

function ajax({
  type = requireParameter("type"),
  url = requireParameter("url"),
  data = requireParameter("data"),
  success = requireParameter("success"),
  error = requireParameter("error"),
  isAsync = requireParameter("isAsync")
  } = {}) {
    console.log(JSON.stringify({
      type,
      url,
      data,
      success,
      error,
      isAsync
    }, null, 2));
};

function requireParameter(name) {
  throw new Error (`Missing parameter "${name}"`);
}

try {
  ajax({
    type: "get",
    url: "http://my.api.io",
    data: {},
    success: () => {},
    error: () => {},
    isAsync: true
  });
} catch (e) {
  console.warn(e.message);
}

{...} = {}第一个参数函数上使用{...}或仅ajax将具有相同的行为。因此,当我测试两个选项中的一个时,我无法断定{...} = {}逻辑的作用。

我在这里提出的问题是:

为什么我们需要对象在ajax函数的第一个参数上等于空对象?

1 个答案:

答案 0 :(得分:1)

在您的特定示例中,您不需要将被破坏的对象默认为空对象,因为您的预期行为是在缺少参数时抛出异常。您可以使用它的属性来默认对象,例如,当没有提供参数时:



function ajax({
  type = requireParameter("type"),
  url = requireParameter("url"),
  data = requireParameter("data"),
  success = requireParameter("success"),
  error = requireParameter("error"),
  isAsync = requireParameter("isAsync")
} = {
    type: "get",
    url: "http://my.api.io",
    data: {},
    success: () => {},
    error: () => {},
    isAsync: true
  }) {
    console.log(JSON.stringify({
      type,
      url,
      data,
      success,
      error,
      isAsync
    }, null, 2));
};

function requireParameter(name) {
  throw new Error (`Missing parameter "${name}"`);
}

try {
  ajax(/* Don't provide anything and use the default */);
} catch (e) {
  console.warn(e.message);
}