[英]Function parameter object destructuring results in undefined variables
I am running Node v6.6.0, which has support for destructuring function arguments: 我正在运行Node v6.6.0,它支持解构函数参数:
function foo ({ a: { b }}) {
// stuff
}
Suppose I want to destructure and access both a
and b
. 假设我要分解并访问
a
和b
。 Sadly the following doesn't seem to work: 遗憾的是,以下内容似乎无效 :
function foo ({ a: { b }}) {
return [a, b]
}
foo({ a: { b: 123 }})
// ReferenceError: a is not defined!
Is this bug in Node or is this the expected behavior for ES6? 这是Node中的错误,还是ES6的预期行为? Shouldn't both
a
and b
be defined in the function? 难道不应该在函数中同时定义
a
和b
吗? If not, why does destructuring have the effect of un-defining a base property name ( a
)? 如果不是,为什么取消结构会取消定义基本属性名称(
a
)的效果?
Is there a way I can use parameter destructuring to get both a
and b
defined in the function? 有没有一种方法可以使用参数解构来获取函数中定义的
a
和b
? I'm explicitly trying to avoid manually destructuring them. 我明确地尝试避免手动破坏它们。
Is this bug in Node or is this the expected behavior for ES6?
这是Node中的错误,还是ES6的预期行为?
This is expected behaviour. 这是预期的行为。 Because
{a: {b}}
doesn't bind a
as a name it just indicates you want to access a
property of the destructured object. 由于
{a: {b}}
没有将a
绑定为名称,因此它仅表示您要访问已分解对象a
属性。
You could use the following. 您可以使用以下内容。
function foo ({ a, a: {b} }) { return [a, b] } console.log(foo({ a: { b: 123 }}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.