ES6 destructuring object assignment function parameter default value

被刻印的时光 ゝ 提交于 2019-12-17 07:50:33

问题


Hi I was going through examples of object destructuring use in passing function parameters here Object Destructuring Demo

function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = **{}**) {
  console.log(size, cords, radius);
 // do some chart drawing
}

 // In Firefox, default values for destructuring assignments are not yet  
 implemented (as described below). 
 // The workaround is to write the parameters in the following way:
   // ({size: size = 'big', cords: cords = { x: 0, y: 0 }, radius: radius =  
      25} = **{}**)

 drawES6Chart({
    cords: { x: 18, y: 30 },
    radius: 30
});

Can anybody let me know what is reason of using empty object assignment at the end of function parameter which I have marked in bold(embedded in double stars) above?


回答1:


If you use it, and call the function with no parameters, it works:

function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
  console.log(size, cords, radius);
 // do some chart drawing
}

drawES6Chart();

if not, an error is thrown:

TypeError: can't convert undefined to object

function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25}) {
  console.log(size, cords, radius);
 // do some chart drawing
}

drawES6Chart();



回答2:


The destructuring with defaults only does its thing when you pass an object which doesn't have the respective properties. The = {} default for the whole parameter allows to not pass an (empty) object at all.

It makes drawES6Chart() equivalent to drawES6Chart({}).




回答3:


You have an object with your default values, but that object is an argument too, so it needs an empty object as a default value for the first argument, which is the object with the filled in values.

function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
}

That, in pseudo code, would be:

function drawES6Chart({**first argument**} = {**default value for first argument**}) {
}



回答4:


That's a default value for the function parameter. Without using = {} JavaScript interpreter throws an error when there is no object passed to the function as it can't destructure an undefined value.



来源:https://stackoverflow.com/questions/38064644/es6-destructuring-object-assignment-function-parameter-default-value

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