When I attempt to use Object destructuring with ev.preventDefault()
, I receive the following error in Chrome:
Uncaught TypeError: Illegal invocation
However, when I use ev.preventDefault()
without destructuring, it works fine. Code that reproduces this issue is shown below.
const button = document.getElementById(`test-button`);
button.onclick = ({ preventDefault }) => {
preventDefault();
};
<button id=test-button type=button>Click me to see the error</button>
Any idea why this is happening? Or how I can use Object destructuring with the Event Object?
preventDefault
is a method that must be invoked on an event object to know which default to prevent. When you do just preventDefault()
, that's not method call syntax and the event object is nowhere to be found: Illegal invocation. Destructuring syntax just accesses the value, it does not automatically bind any functions.
button.onclick = (e) => {
const { preventDefault } = e; // like const preventDefault = e.preventDefault;
preventDefault(); // does not work, unlike preventDefalt.call(e)
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With