简体   繁体   中英

Parameter Object Destructuring with Required Values and Empty Object

Using ES6 parameter object destructuring we can require the presence of certain properties, as well as, provide default values . Dr. Axel Rauschmayer said in the Six nifty ES6 tricks article that parameter default values are only evaluated when they are actually used.

The next example will provide more context about what I do not understand:

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);
}

Having the {...} = {} or just {...} on the ajax first argument function will have the same behavior. So when I test one of the two options I can not conclude what does the {...} = {} logic do.

The question that I made here is:

Why do we need the object to be equal to an empty object on the first argument of the ajax function?

In your particular example, you don't need to default the destructed object to an empty object since your intended behaviour is to throw an exception when a parameter is missing. You could default the object with it's properties like so for when no argument is provided:

 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); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM