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()

3
  • You seem to be confused, you definitely can't do this in Java Commented Mar 19, 2022 at 21:47
  • "other languages like Java allow me to overwrite/clone the current instance by either construct overload or this overwrite." - no, they don't either Commented Mar 19, 2022 at 21:47
  • Maybe it was only a dream. Commented Mar 19, 2022 at 21:48

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Maybe even this.constructor('Ferrari', 2021) - oh, wait, that works only in ES5 but not with class :-/
This is correct, but not this. :-(
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++.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.