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 here

Output:

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

I thought arrays were sent by reference while other values are copied by value. This answer supports the same. What's happening here?

I need to access variables of MyClass in a neat way, how do I do it?

2 Answers2

3

This is because

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

created a new array.

let {points} = this;

originally points to the points array belonging to the class instance, but

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

changes the reference.

You can use .push to maintain the reference as:

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

EDIT to explain more verbose-ally:

[...points, {x: 20, y:20}] creates a new array, so assigning the new array to points does not change the data the points variable(think pointer) points to, but rather changes the pointer itself to a new memory location.

Ayush Gupta
  • 7,958
  • 7
  • 50
  • 85
  • 1
    As I already explained, `[...points, {x: 20, y:20}]` created a new array, so assigning the new array to `points` does not change the data the `points` variable(think pointer) _points_ to, but rather changes the pointer itself to a new memory location. – Ayush Gupta Oct 20 '18 at 10:48
  • so it is indeed assigning by reference! just understood the point made: i'm throwing away _that_ reference by assigning a new one – Saravanabalagi Ramachandran Oct 20 '18 at 10:50
2

When using let {points} = this;, the points variable contains a value and that value is the reference to your array. So when you edit a property of that array as is done in the answer you linked, you modify the referenced array.

But in your case you use points = [...points, {x: 20, y:20}];. Here you assign a new value (a reference to your newly created array) to points, and so the reference to the old array is gone.

In this case you can simply use this.points = [...points, {x: 20, y:20}]; in order to assign it to the this, or push your object directly to this.points using this.points.push({x: 20, y:20}). (For the latter, you don't need to use a destructuring assignment in the first place.)

Ivar
  • 5,377
  • 12
  • 50
  • 56