1

is it possible to clone idiomatically a javascript class instance from within of its own method? Others languages like Java allow me to overwrite/clone the current instance by either construct overload or this overwrite. Javascript does not seems to like it, and throws the error SyntaxError: Invalid left-hand side in assignment. THere is an example below for this verbose explanation.

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }

  renew() {
    this = new Car('Ferrari', 2021);
    return this
  }
}

car = new Car('Ford', 206)
car.renew()
Shawn
  • 10,931
  • 18
  • 81
  • 126

2 Answers2

1

this can't be assigned to. For what you want, you must either:

  • Return a new instance from the method, and reassign it outside the method

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }

  renew() {
    return new Car('Ferrari', 2021);
  }
}

let car = new Car('Ford', 206)
car = car.renew()
console.log(car.year);
  • Or mutate the instance inside the method

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }

  renew() {
    Object.assign(this, new Car('Ferrari', 2021));
  }
}

let car = new Car('Ford', 206)
car.renew()
console.log(car.year);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

No, it is not possible to do this. this is immutable. Your options would either be to modify the properties of the class, or create a new class instance and assign it to a your variable in enclosing scope.

I'm also not sure what language you are using that allows assignment to a this reference. It's not possible in Java, C#, Scala, or Ruby. It's technically possible in Python, but doesn't have the semantics you describe (e.g. it does not mutate the object). You can't even do it in C++.

Nick Bailey
  • 3,078
  • 2
  • 11
  • 13