Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda