For the More Curious: Closures

Earlier we mentioned that developers often prefer to use anonymous functions as callbacks instead of named functions. addThumbClickHandler illustrates why an anonymous function is a better solution.

Let’s say you tried to use a named function, clickFunction, for the callback. Inside of that function, you have access to the event object because it will be passed in by addEventListener. But the body of clickFunction has no access to the thumb object. That parameter is only accessible inside the addThumbClickHandler function.

function clickFunction (event) { event.preventDefault(); setDetailsFromThumb(thumb); // <--- This will cause an error } function addThumbClickHandler(thumb) { thumb.addEventListener('click', ...

Get Front-End Web Development: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.