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

234
Views
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 answers
Answer question

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