[英]what does the syntax in function foo({ defaultValue = {} } = {}) mean?
I came across this function the other day 前几天我遇到了这个功能
function foo({ defaultValue = {} } = {}) {
...
}
I don't understand what the { defaultValue = {} } = {}
part exactly means. 我不明白
{ defaultValue = {} } = {}
部分的确切含义。 I understand that there is an object property destructing for defaultValue
, and there is a default argument set to {}
if there is no arguments passed to this function. 我知道有一个对象属性会破坏
defaultValue
,并且如果没有传递给该函数的参数,则会将默认参数设置为{}
。 However I am not sure about what the combination is doing. 但是我不确定该组合在做什么。 Can someone explain to me?
有人可以向我解释吗?
I understand that there is an object property destructing for
defaultValue
, and there is a default argument set to{}
if there is no arguments passed to this function.我知道有一个对象属性会破坏
defaultValue
,并且如果没有传递给该函数的参数,则会将默认参数设置为{}
。
Yes, that's what 是的那就是
function foo({ defaultValue } = {}) {
would be doing. 会做的。 The additional
= {}
in 附加
= {}
function foo({ defaultValue = {} } = {}) {
// ^^^^
now provides a default value for the defaultValue
variable, when the property does not exist in the object or is undefined
. 当对象中不存在该属性或
undefined
该属性时,现在为defaultValue
变量提供一个默认值。
It's a nice way of guaranteeing that foo
will have access to the defaultValue
property of the object argument passed in - 这是保证
foo
可以访问传入的对象参数的defaultValue
属性的一种好方法-
Given - 鉴于-
function foo ({ bar = 1 } = {}) { console.log(bar) } foo() // => 1 foo({}) // => 1 foo({bar: 2}) // => 2
However watch out for null
specifically - 但是请特别注意
null
foo(null) // => TypeError: cannot read property "bar" of null
If we skip the last ... = {}
portion, then it will not be able to read bar
in the undefined
instance - 如果我们跳过最后
... = {}
部分,那么它将无法读bar
在undefined
情况下-
function foo ({ bar = 1 }) { console.log(bar) } foo() // TypeError: Cannot destructure property "bar" of undefined or null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.