0

I want to override one Element.prototype function:

  const originalAppendChild = Element.prototype.appendChild;

  Element.prototype.appendChild = (el) => {
    console.log("Override!!!");
    return originalAppendChild.apply(this, [el]);
  };

But when I then run:

document.body.appendChild(document.createElement("div"));

I get:

Override!!!
VM406:5 Uncaught TypeError: Illegal invocation
    at HTMLBodyElement.Element.appendChild (<anonymous>:5:36)
    at <anonymous>:1:15

Where line 5:36 refers to the .apply(this, [el]); part. Which means it this the apply method who is throwing this error.

I have tried to figure out, and it seems the problem comes from this, but I am at loss how to properly set it (if that's the cause).

PedroD
  • 4,310
  • 8
  • 38
  • 75
  • 1
    fat arrow changes this, – epascarello Oct 15 '19 at 14:16
  • Don't define member methods with arrow functions, define them with pre-ES2015 function expresions, which have their own lexical `this` and `arguments` as opposed to arrow functions. – Patrick Roberts Oct 15 '19 at 14:18
  • 1
    You can also use `call` instead of `apply` if you want to forward one argument. – Christian C. Salvadó Oct 15 '19 at 14:20
  • OMG, I would never have guessed this one. Is there any documentation I should have read and I missed? How did you know the arrow function was the culprit? This is soooo dark...! – PedroD Oct 15 '19 at 14:22
  • 1
    @PedroD there is plenty of documentation on the subject, such as [here on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this) – Patrick Roberts Oct 15 '19 at 15:05

0 Answers0