Closure classic

Developer
Size
1,842 Kb
Views
36,432

How do I make an closure classic?

What is a closure classic? How do you make a closure classic? This script and codes were developed by Nick Williams on 27 August 2022, Saturday.

Closure classic Previews

Closure classic - Script Codes HTML Codes

<!DOCTYPE html>
<html >
<head> <meta charset="UTF-8"> <title>closure classic</title>
</head>
<body> <p>This is a classic example of where you need a closure. Notice that every button reports the same value (the final value of <code>i</code>). The reason for this is each function shares the same scope, so each callback refers to the exact same variable <code>i</code>.</p>
<button class="without-closure">Click</button>
<button class="without-closure">Click</button>
<button class="without-closure">Click</button>
<button class="without-closure">Click</button>
<button class="without-closure">Click</button>
<p>The problem is sharing of scope, so the solution is of course to create a new scope (via a closure) for each event listener. This sounds complex but the solution is always the same: <em>create your callback/event listener within another function:</em></p>
<button class="with-closure">Click</button>
<button class="with-closure">Click</button>
<button class="with-closure">Click</button>
<button class="with-closure">Click</button>
<button class="with-closure">Click</button>
<p>The reason for this is that JavaScript (confusingly) has function-level scope, so we call another function to create a new scope.</p> <script src="js/index.js"></script>
</body>
</html>

Closure classic - Script Codes JS Codes

var buttons = document.querySelectorAll(".without-closure");
for(var i = 0, length = buttons.length; i < length; i++) { buttons[i].addEventListener("click", function() { alert(i); },false);
}
buttons = document.querySelectorAll(".with-closure");
function createCallback(value) { return function() { alert(value); }
}
for(var i = 0, length = buttons.length; i < length; i++) { buttons[i].addEventListener("click", createCallback(i),false);
}
Closure classic - Script Codes
Closure classic - Script Codes
Home Page Home
Developer Nick Williams
Username WickyNilliams
Uploaded August 27, 2022
Rating 3
Size 1,842 Kb
Views 36,432
Do you need developer help for Closure classic?

Find the perfect freelance services for your business! Fiverr's mission is to change how the world works together. Fiverr connects businesses with freelancers offering digital services in 500+ categories. Find Developer!

Nick Williams (WickyNilliams) Script Codes
Create amazing marketing copy with AI!

Jasper is the AI Content Generator that helps you and your team break through creative blocks to create amazing, original content 10X faster. Discover all the ways the Jasper AI Content Platform can help streamline your creative workflows. Start For Free!