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

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

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