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

224
Visualizações
can't use "this" on both sides of assignment

I want to make my function addHat() reusable for other person objects as well, so I decided to use this instead of exact name of the person and pass my other objects as this by addHat.call() and addHat.apply() methods.

ie. I want to shallow copy the person object using spread (having new references for all of the properties.

However, it doesn't work using this on both sides of the assignment

let person1 = {
    a: "a",
    hats: [],
  gloves: []
};

function addHat(newHat, ...params) {
    this = {
        ...this,
        hats: [...this.hats, newHat, ...params],
    };
}

addHat.call(person1, "hatA");
console.log(person1.hats);

But perfectly works when using the name directly instead:

let person1 = {
    a: "a",
    hats: [],
  gloves: []
};


function addHat(newHat, ...params) {
  person1 = {
    ...person1,
        hats: [...person1.hats, newHat, ...params],
    };
}

addHat.apply("uselessThis", ["hatA", "hatB"]);
console.log(person1.hats);

Can you help me to make this function reusable with the current format? (using spread and shallow copying of the object properties)

every hint or help will be much appreciated.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I think that it's easier if you pass persona as an argument of the function.

Try to avoid the use of this in js because it can become tricky to debug

let person1 = {
  a: "a",
  hats: [],
  gloves: []
};

function immutableAddHat(person, ...newHats) {
  return {
    ...person,
    hats: [...person.hats, ...newHats],
  };
}

function addHat(...newHats) {
  Object.entries(this).forEach(([k, v]) => {
    this[k] = v
  })

  this.hats = [...this.hats, ...newHats]

}

const newPerson1 = immutableAddHat(person1, "hatA");

console.log(newPerson1.hats);

addHat.call(person1, "Hatb")

console.log(person1)

I added the method that uses this

about 4 years ago · Santiago Trujillo 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