Search code examples
javascriptarraysprototypal-inheritanceprototype-programmingarray.prototype.map

Javascript prototype and modify original object


How can we update passed object in prototype? I have created similar prototype as Array.reverse, but how I can modify original object?

Array.prototype.myReverse = function() {
  let arr = [];
  for (let i = 0; i < this.length; i++) {
    arr.unshift(this[i]);
  }
  return arr;
}

let a = [9, 0, 3, 4];
console.log("Before ", a); // [9, 0, 3, 4]
console.log("reverse - ", a.myReverse()); // [4, 3, 0, 9]
//not modifying original object , how to modify original object
console.log("After ", a); // [9, 0, 3, 4]

I have check few examples but I didnt get how to update orginal object inside prototype How can we crate a prototype which will update original object (Careful: reverse is destructive -- it changes the original array.) If not possible for predefined Array then how we can create similar MyArray to write a prototype for updating original object.


Solution

  • You cannot assign this directly, but you can still change its properties. So keeping in the style of the code you posted, you could do something along the lines of:

    Array.prototype.myReverse = function() {
      let arr = [...this]
      for (let i = 0; i < this.length; i++) {
        this[i] = arr.pop()
      }
    }