0
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在这里

输出:

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

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

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

4

2 回答 2

3

这是因为

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

创建了一个新数组。

let {points} = this;

最初指向属于类实例的点数组,但是

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

更改参考。

您可以使用.push以下方式维护参考:

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

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

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

于 2018-10-20T10:41:21.550 回答
2

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

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

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

于 2018-10-20T10:43:58.503 回答