我在 JS 教程页面找到了以下代码,但我不确定它是做什么的以及它是如何工作的。你能解释一下它的用途和作用吗?
//来源是:https://javascript.info/property-accessors
let user = {
name: "John",
surname: "Smith",
get fullName() {
return `${this.name} ${this.surname}`;
},
set fullName(value) {
[this.name, this.surname] = value.split(" "); <<<<<<<<<<<<<<<<<<<<<<<<<
}
};
//set fullName 使用给定的值执行。user.fullName = "Alice Cooper";
alert(user.name); // Alice
alert(user.surname); // Cooper
最佳答案
value.split
创建一个包含两个元素的列表(在这种特殊情况下 "Alice Cooper"
=> ["Alice", "Cooper"]
)并将元素解包到 [this.name, this.surname]
this.name
包含数组的第一个元素和 this.surname
包含第二个元素。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
关于javascript - 属性访问是如何工作的,下面这行有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63502987/