public
Created

Trying To Mimic LET Functionality In JavaScript Using Self-Executing Functions

  • Download Gist
demo.htm
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
<!DOCTYPE html>
<html>
<head>
<title>Inline Functions Create Sandboxes For Variable Binding</title>
<script type="text/javascript">
 
 
// Create a buffer to hold our function - these will invoked
// at the end to demonstrate variable binding.
var methodBuffer = [];
 
 
// We'll create 5 functions.
for (var i = 0 ; i < 5 ; i++){
 
// Create a "unexpected behavior" binding to i.
var j = i;
 
// Create an inline, self-executing function to create a
// closure and sandbox for the execution of this loop
// iteration.
(function( i ){
 
// Create our testing function - notice that the
// console.log() method is referencing "i", which is
// a variable defined by our self-executing function,
// and the variable, "j", which is a variable defined
// in the FOR loop block.
var method = function(){
console.log( i, "-", j );
};
 
// Add it to the buffer - we'll see if the binding
// holds up afterward.
methodBuffer.push( method );
 
}).call( this, i );
// Notice that when we invoke this inline function,
// we're binding the execution context AND passing in
// the current value of [i].
 
}
 
 
// Now, test the methods and the variable bindinds.
while (methodBuffer.length){
 
// Get the front method (changes the length of the array).
var method = methodBuffer.shift();
 
// Invoke it to see if the "console.log(i)" variable
// binding is referencing the correct value.
method();
 
}
 
 
</script>
</head>
<body>
<!-- Left intentionally blank. -->
</body>
</html>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.