Skip to content

Instantly share code, notes, and snippets.

@gerisztein
Last active March 28, 2016 13:41
Show Gist options
  • Save gerisztein/e5833da5969c9368cdb5 to your computer and use it in GitHub Desktop.
Save gerisztein/e5833da5969c9368cdb5 to your computer and use it in GitHub Desktop.
We need to talk about closures (variables and lexical scope)
var text = 'Some text';
function showText () {
alert(text);
}
showText(); // Alert “Some text”
var text = 'Some text';
function showText () {
alert(text);
}
function dontChangeText () {
var text = 'The text has not been changed';
alert(text);
showText();
}
function changeText () {
text = 'The text has been changed';
alert(text);
showText();
}
showText();
// Alert "Some text"
dontChangeText();
// Alert "The text has not been changed" then "Some text"
changeText();
// Alert "The text has been changed" twice
function outerFunction () {
var a = 'First value';
function innerFunction () {
var b = ‘second value’;
alert(a + ‘ and ‘ + b);
innerFunction2();
function innerFunction2 () {
var c = ‘third value’;
alert(a + ’, ‘ + b + ‘ and ‘ + c);
}
}
innerFunction();
}
function outerFunction () {
var a = 'Hello! ';
var b = 'What is your name?';
function innerFunction () {
a = 'Hi! ';
b = 'My name is Lucas!';
alert(a + b);
}
alert(a + b);
innerFunction();
}
outerFunction();
// Alerts "Hello! What is your name?" and
// "Hi! My name is Lucas!" respectively
function showText () {
var text = 'Some text';
function displayText () {
alert(text);
}
return displayText;
}
var myFunction = showText();
myFunction(); // Return “Some text”
function counter () {
counter = 0;
function add () {
counter += 1;
}
add();
return counter;
}
function counter () {
var counter = 0;
function add() {
return counter += 1;
}
return add;
}
var myCounter = counter();
myCounter(); // Return 1
myCounter(); // Return 2
myCounter(); // Return 3
function counter () {
var counter = 0;
function changeValue(value) {
counter += value;
}
function increment () {
changeValue(1);
}
function decrement () {
changeValue(-1);
}
function value () {
return counter;
}
function reset () {
counter = 0;
}
return {
increment: increment,
decrement: decrement,
reset: reset,
value: value
};
}
var myCounter = counter();
myCounter.value(); // Return 0
myCounter.increment(); // Increase the counter
myCounter.increment(); // Increase the counter again
myCounter.value(); // Return 2
myCounter.decrement(); // Decrease the counter
myCounter.value(); // Return 1
myCounter.reset(); // Reset the counter
myCounter.value(); // Return 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment