Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created January 17, 2012 15:36
Show Gist options
  • Save bennadel/1627095 to your computer and use it in GitHub Desktop.
Save bennadel/1627095 to your computer and use it in GitHub Desktop.
Trying To Mimic LET Functionality In JavaScript Using Self-Executing Functions
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment