Event Handler Deconstruction in JavaScript

Adam Beck
Adam Beck
Feb 25, 2017 · 1 min read

Anyone who’s familiar with ES6 has surely run across deconstruction. It’s a pretty neat feature which lets you cut down on writing line after line of properties plucking on objects.

This feature is really useful when you want a property off a function parameter, such as an event handler.

You could go even deeper and do the following.

However, things get a bit weird when you start deconstructing methods off of the event object (and any other prototype function that uses the this keyword).

Consider the following example. If we have a form element and we want to stop the form submitting when the enter key is hit we’d call preventDefault.

You’d expect that code would work, but the form still submits. Why?!. Well, what’s happening is that the preventDefaultfunction is being called in a different context. It’s not longer being called in the typical way, such as event.preventDefault(). Deconstructing the function off of the event and calling it causes the thiscontext to change from the event object, to the nearest context (probably the window). This doesn’t do anything. Resulting in the event to continue propagating and the form gets sent. Lame.

Moral of the story? If you suspect that a function uses the this keyword, don’t deconstruct functions off of their objects / prototypes. However, if a function does not use this, deconstruct away.