由于我不是很熟悉新的当谈论功能的默认参数时。功能1:
code>函数m1({x = 0,y = 0} = {}){ return [x,y]; }功能2:
函数m2({x,y} = {x:0,y:0}){ return [x,y]; }解决方案
尝试传递一些东西到你的函数:
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]您的第一个语法( m1({x = 0,y = 0} = {}) )做了三件事:
- 首先,它为函数提供一个默认的第一个参数,这是一个空对象。如果没有给出第一个参数( m1()),则使用默认的空对象(即,它变为 m1({}))
- 其次,您的代码提取 x 和 y
- 如果任何一个是 undefined ,它将被赋予默认值 0 。
m2({x,y} = {x:0,y:0 })做了不同的事情:
- 首先它为函数提供一个默认的第一个参数,对象 {x:0,y:0} 。如果没有传入第一个参数,则使用该对象。如果除未定义之外的任何参数都被传递,那么使用该值。
- 其次,代码提取 x 和 y 属性。如果他们是 undefined ,那就是你会得到的。
选项(具有使用更多默认值进行破坏的默认值的参数)几乎是您想要的。第二个选项意味着如果传递参数,则您的代码对于属性没有明智的/有用的默认值。
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]; }解决方案
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.
更多推荐
功能的JavaScript默认参数
发布评论