1

I have found this problem with spread operator when cloning a class instance. The methods context remain with the original instance. Somebody knows how to fix it?

class Person {
   constructor(name) {
      this.name = name;
      this.setName = name => {
         this.name = name;
      };
   }
}

const a = new Person('John');
console.log(a.name); //John

const b = { ...a };
console.log(b.name); //John

b.setName('Paul');
console.log(b.name); //John

console.log(a.name); //Paul

Juanjo
  • 11
  • 1
  • You shouldn't be cloning classes with spread in the first place, since you also lose the class. – VLAZ Nov 25 '21 at 12:22
  • This seems like [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) what is the overall task you want to solve? – VLAZ Nov 25 '21 at 12:26
  • See this: - https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object - https://stackoverflow.com/questions/41474986/how-to-clone-a-javascript-es6-class-instance – Diogo Simões Nov 25 '21 at 12:30
  • If you want to clone an instance, create a method in the class that returns a new instance. – Yousaf Nov 25 '21 at 12:48

0 Answers0