属性访问的工作原理以及以下几行是做什么的?

问题描述

我在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

,
user.fullName = "Alice Cooper";

调用set fullName中的user

set fullName(value) {
    [this.name,this.surname] = value.split(" "); <<<<<<<<<<<<<<<<<<<<<<<<<
}

然后对给定的字符串“ Alice Cooper”执行.split,将其按字符串中的空格分成数组。因此,"Alice Cooper".split(" ")的结果是一个数组["Alice","Cooper"]

然后,此数组立即destructured进入user对象的namesurname属性。