在下面的示例中,为什么 whois() 函数可以访问 displayName2 和 name1?
function whois({displayName: displayName2, fullName: {firstName: name1}}){
console.log(`${displayName2} is ${name1}`)
}
let user = {
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe"
}
}
whois(user) // "jdoe is John"
对于未经训练的人来说,它看起来应该有权访问 displayName 和 fullName.firstName。解构看起来就像 JSON 的反转。
幕后发生了什么?
最佳答案
displayName
和 firstName
为 assigned new names - displayName2
和 firstName1
可以接受,并且要访问这些值,您需要使用别名。
由于只有别名被定义为变量,尝试使用旧名称访问值将引发“变量未定义”错误。
const destructure1 = ({ a: aa }) => console.log(aa);
destructure1({ a: 5 }); // gets the value
const destructure2 = ({ a: aa }) => console.log(a);
destructure2({ a: 5 }); // throw an error because a is not defined
此外,当使用 computed property names 进行解构时,您必须将其分配给新的变量名称:
const prop = 'a';
const destructure1 = ({ [prop]: aa }) => console.log(aa);
destructure1({ a: 5 }); // gets the value
关于javascript - 对解构函数参数感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46878587/