Javascript 解构:通过引用复制 class 变量以允许分配和修改值

Javascript destructuring: copy class variables by reference to allow assigning and modifying values

class MyClass {
  constructor() {
    this.points = [];
    // I need to call this after the components are mounted
    // So keeping the setup separate
    this.setupMyClass();
  }

  setupMyClass() {
    let {points} = this;
    points = [...points, {x: 20, y:20}];

    // ugly code 
    // need to repeat 'this.' everytime I use the variable
    // this.points = [...this.points, {x: 20, y: 20}];

    console.log('points', points);
    console.log('this.points', this.points);
  }
}

myClassInstance = new MyClass();

JSFiddle here

输出:

points: [{..}]
this.points: []

我以为数组是按引用发送的,而其他值是按值复制的。这个 支持相同。这里发生了什么?

我需要以简洁的方式访问 MyClass 的变量,我该怎么做?

这是因为

[...points, {x: 20, y:20}];

创建了一个新数组。

let {points} = this;

原本指向属于class实例的points数组,但是

points = [...points, {x: 20, y:20}];

更改引用。

您可以使用 .push 将引用维护为:

points.push({x: 20, y:20});

编辑以解释更详细的盟友:

[...points, {x: 20, y:20}] 创建一个新数组,因此将新数组分配给 points 不会将 points 变量(认为指针) points 的数据更改为,而是将指针本身更改为新的内存位置。

使用 let {points} = this; 时,points 变量包含一个值,该值是对数组的引用。 因此,当您按照链接的答案编辑该数组的 属性 时,您修改了引用的数组。

但在你的情况下你使用 points = [...points, {x: 20, y:20}];。在这里,您为 points 分配了一个新值(对新创建的数组的引用),因此对旧数组的引用消失了。

在这种情况下,您可以简单地使用 this.points = [...points, {x: 20, y:20}]; 将其分配给 this,或者使用 this.points.push({x: 20, y:20}) 将您的对象直接推送到 this.points。 (对于后者,您一开始就不需要使用解构赋值。)