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



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1