2016-06-27 87 views
3

,您好我所经历的对象拆解利用的例子在传递函数的参数在这里Object Destructuring DemoES6解构对象赋值函数参数的默认值

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

任何人都可以让我知道什么是使用在最后空对象分配的原因我在上面用粗体标出了(嵌入双星)函数参数的函数吗?

回答

7

如果你使用它,并调用该函数不带参数,它的工作原理:

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

 
drawES6Chart();

如果不是,引发错误:

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

4

您有一个包含默认值的对象,但该对象也是一个参数,因此它需要一个空对象作为第一个参数的默认值,该参数是具有填充值的对象。

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

也就是说,在伪代码将是:

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

当你传递一个对象不具有各自的特性与默认的解构只做它的事。整个参数的缺省值= {}允许根本不传递(空)对象。

它使得drawES6Chart()等于drawES6Chart({})

2

这是函数参数的默认值。没有使用= {}当没有对象传递给函数时,JavaScript解释器会抛出错误,因为它无法解构undefined值。