Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda