Last active
November 2, 2016 10:55
-
-
Save brody4hire/f519b64a4eb072527f52cd64f9fe628f to your computer and use it in GitHub Desktop.
A simple case for JavaScript closures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREDIT FOR INSPIRATION: | |
http://www.w3schools.com/js/js_function_closures.asp | |
ORIGINAL PURPOSE: | |
This is to help address a Flow Based Programming discussion comment at: | |
https://groups.google.com/d/msg/flow-based-programming/SckVpqE5IZM/ldeBRp5hAwAJ | |
The W3 schools sample above presents an easy to understand explanation of | |
closures but I do not think it makes a strong enough case WHY. | |
I will attempt to present an improved case along with a similar sample | |
that should still be easy to understand. | |
SEQUENTIAL ID DILEMMA: | |
A programmer wants increasing record ID values. It should be possible to start | |
with an arbitrary value and it should be possible to deal with multiple kinds or | |
tables of records. | |
FIRST ATTEMPT: | |
var recordId = 101; | |
function getNextRecordId() { | |
return recordId++; | |
} | |
Issues: | |
* Extra global variable | |
* Risk that another piece of code may change recordId | |
* Need to copy, paste, and adapt this code to support a second table | |
SOLUTION WITH CLOSURE: | |
function getNextIdHelper(firstId) { | |
var currentId = firstId; | |
return function() { | |
return currentId++; | |
} | |
} | |
QUICK TEST: | |
let getNextId = getNextIdHelper(101); | |
console.log('first id: ' + getNextId()); | |
console.log('second id: ' + getNextId()); | |
console.log('third id: ' + getNextId()); | |
DEMO IN BROWSER: | |
https://jsfiddle.net/brodybits/gje79sxv/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment