JavaScript default parameters for function

a 夏天 提交于 2019-12-07 05:21:15

问题


I can fully understand ECMAScript 6 has created a lot of potential way of handling with functions such as arrow functions.

Since I'm not very familiar with the new stuff, when talking about default parameters for a function. How to interpret the differences between the following way of defining functions:

Function 1:

function m1({x = 0, y = 0} = {}) {
  return [x, y];
}

Function 2:

function m2({x, y} = { x: 0, y: 0 }) {
  return [x, y];
}

回答1:


The difference is clear when you try passing something to your functions:

m1({}) // [0, 0]
m1({z: 1}) // [0, 0]
m1({x: 1}) // [1, 0]

m2({}) // [undefined, undefined]
m2({z: 1}) // [undefined, undefined]
m2({x: 1}) // [1, undefined]

Your first syntax (m1({x = 0, y = 0} = {})) does three things:

  • First, it provides a default first argument to the function, which is an empty object. If no first argument is given (m1()) then the default empty object is used (i.e. it becomes m1({}))
  • Second, your code extracts the x and y properties from that object.
  • If either is undefined, it is given a default value 0.

m2({x, y} = { x: 0, y: 0 }) does something quite different:

  • First it provides a default first parameter to the function, which is the object {x: 0, y: 0}. If no first argument is passed, that object is used. If any argument other than undefined is passed, that value is used instead.
  • Second, the code extracts the x and y properties from that object. If they are undefined, that's what you'll get.

The first option (a parameter with a default value that is destructured with more default values) is almost certainly what you want. The second option means that your code does not have sensible/useful default values for the property if arguments are passed.




回答2:


m1 provides default values for x and y, whereas m2 merely destructures x and y from a provided object and only provides default values if the object itself isn’t provided:

  • m1({}) will return [0, 0]
  • m2({}) will return [undefined, undefined]
  • Both m1() and m2() will return [0, 0]

  • m1({x: 10}) will return [10, 0]
  • m2({x: 10}) will return [10, undefined]

So, if m2 receives an object, it will destructure the available values to the variables x and y. If any of them is missing, it’s undefined. Only if the whole object is missing, it’ll provide a default object ({ x: 0, y: 0 }) from which to get the values.

m1, however, provides default values for both properties even if they’re missing. And if the whole object is missing, it’ll still provide those default values.



来源:https://stackoverflow.com/questions/42093572/javascript-default-parameters-for-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!