前几天我遇到了这个函数
function foo({ defaultValue = {} } = {}) {
...
}
我不明白{ defaultValue = {} } = {}
部分到底是什么意思。我知道有一个对象属性对defaultValue
进行析构,如果没有传递给此函数的参数,则有一个默认参数设置为 {}
。但是,我不确定该组合在做什么。有人可以向我解释一下吗?
我知道有一个对象属性为
defaultValue
析构,如果没有传递给此函数的参数,则有一个默认参数设置为{}
。
是的,就是这样
function foo({ defaultValue } = {}) {
会做的。附加= {}
function foo({ defaultValue = {} } = {}) {
// ^^^^
现在为 defaultValue
变量提供默认值,当属性在对象中不存在或undefined
时。
这是保证foo
可以访问传入的对象参数的 defaultValue
属性的好方法 -
鉴于-
function foo ({ bar = 1 } = {}) {
console.log(bar)
}
foo() // => 1
foo({}) // => 1
foo({bar: 2}) // => 2
但是要特别注意null
-
foo(null) // => TypeError: cannot read property "bar" of null
如果我们跳过最后... = {}
部分,那么它将无法读取undefined
实例中的bar
-
function foo ({ bar = 1 }) {
console.log(bar)
}
foo()
// TypeError: Cannot destructure property "bar" of undefined or null