Skip to content

Instantly share code, notes, and snippets.

@lizlongnc
Last active August 29, 2015 14:07
Show Gist options
  • Save lizlongnc/21d87349611012d99f94 to your computer and use it in GitHub Desktop.
Save lizlongnc/21d87349611012d99f94 to your computer and use it in GitHub Desktop.
JS Closure
Closure is a central idea in JavaScript.
The context of an inner function includes the sclope of the outer function.
An inner function enjoys that context even after the parent functions have returned.
function scope works like block scope.
Global:
var names = ['zero', 'one', 'two',
'three', 'four', 'five', 'six',
'seven', 'eight', 'nine'];
var digit_name = function (n) {
return names[n];
};
alert(digit_name(3)); // 'three'
Slow - now names is private in digit_name function because it's inside the function therefore it's inside the function scope and will not conflict with any globals:
var digit_name = function (n) {
var names = ['zero', 'one', 'two',
'three', 'four', 'five', 'six',
'seven', 'eight', 'nine'];
return names[n];
};
alert(digit_name(3)); // 'three'
Closure:
// optimized - notice () wrapping: = (function...
var digit_name = (function () {
var names = ['zero', 'one', 'two',
'three', 'four', 'five', 'six',
'seven', 'eight', 'nine'];
return function (n) {
return names[n]
);
}());
// returns a function that returns the value from names[n]
// once the assignment has been done, the function has returned
// digit_name is being assigned what is being returned by the return function, not the initial function
alert(digit_name(3)); // 'three'
// the return function (inside) continues to enjoy access to the variable digit_name even after the function that created digit_name variable has finished its work
Another example of Closure:
function fade(id) {
var dom = document.getElementById(id),
level = 1;
function step() {
var h = level.toString(16); // 16 - use hex representation of the string
dom.style.backgroundColor =
'#ffff' + h + h;
if(level < 15) {
level += 1;
setTimeout(step, 100); // allows for a more gradual fade effect
}
}
setTimeout(step, 100);
}
In the above, after the parent function (fade) has returned, the inner function (step) continues evaluating the if(level < 15) statement and has access to the vars level and dom. These vars are not copies, the inner function is bound to them.
Because of the way function scopes work, the above function can be called on 2 dom elements at the same time, and will not interfere with each other b/c each creates its own dom, level, and step values which are completely distinct and held inside of their own scope from all other invocations.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment