Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Javascript - Reassignment of class instance from its own method

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!