Search code examples
javascriptdestructuringecma

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

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?


Solution

  • 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.