This version of WWWTC is dedicated to closures. We can use closures and functional programming in general to create elegant, succinct solutions, but sometimes we can also create subtle bugs.
Exhibit A. The C# developer who wrote this code expected DoSomething to be invoked with the values 0 through 9, but something is terribly wrong.
for (int counter = 0; counter < 10; counter++) { ThreadPool.QueueUserWorkItem( state => DoSomething(counter) ); }
What’s the problem?
A JavaScript developer is working with the following markup.
<div class="header"> <div class="detail">Detail 1 …</div> </div> <div class="header"> <div class="detail">Detail 2 …</div> </div> <!-- and so on-->
When the user clicks inside a detail section, the developer wants to change the background color of all the other header sections. Thinking of one way to achieve this behavior, the developer first tests the jQuery not method.
$(function() { $(".header").each(function() { alert($(".header").not(this).length); return false; }); });
This code correctly alerts the user once and displays the total number of headers – 1.Emboldened with this proof of concept, the developer puts in the required CSS manipulation and embeds the code into a click event handler.
$(function() { $(".header").each(function() { $(".detail", this).click(function() { $(".header").not(this).css("background-color", "red"); }); }); });
Suddenly, things aren’t working and every header section turns red. What went wrong?