Skip to content

Instantly share code, notes, and snippets.

@kellishouts
Created January 29, 2015 18:15
Show Gist options
  • Save kellishouts/40d3c73b14a7368437c8 to your computer and use it in GitHub Desktop.
Save kellishouts/40d3c73b14a7368437c8 to your computer and use it in GitHub Desktop.
Closures, Callbacks, Scope
Closure
a closure is the local variables for a function - kept alive after the function has returned
a closure is a stack-frame which is not deallocated when the function returns
// scope
function outer_scope() {
var foo = 1;
console.log ('foo', foo);
function inner_scope() {
var foo = 2;
console.log ('foo', foo);
}
inner_scope();
}
outer_scope();
// callbacks
function makeNumbers(i, cb) {
var num1, num2, num3;
num1 = i;
num2 = i*2;
num3 = i*i;
cb(num1, num2, num3);
}
makeNumbers(42,
function printAndAdd(a, b, c) {
console.log(a, b, c);
console.log('sum', a+b+c);
} );
// closure
var getName, getCharacterClass;
function healerPlz() {
var name = 'Codex';
var characterClass = 'Priest';
getName = function() {return name;};
getCharacterClass = function() {return characterClass};
}
healerPlz();
console.log(getName() );
console.log(getCharacterClass() );
console.log(name);
// callback
function retrieveDatabaseEntry(recordNum, cb) {
var db = ['foo', 'bar', 'bletch', 'quux', 'bulbasaur', 'charmander', 'squirtle', '42'];
var result = db[recordNum];
cb(result);
}
function printEntry(val) {
console.log('retrieved value: ', val);
}
retrieveDatabaseEntry(5, printEntry);
// scope
var item = 'THE HOLY GRAIL' // CAN'T TOUCH THIS
function building() {
var item = 'whiteboards';
console.log(item);
room();
function room() {
var item = 'cookies';
console.log(item);
}
}
// closure
function getStats(a, b) {
var vals = {
min: (a < b) ? a : b,
max: (a > b) ? a : b
}
return function() { return vals; };
}
console.log( getStats(42, 9000) () );
console.log( getStats(9000, 42) () );
// callback
function prepareAndDeliverFood(food, cb) {
console.log('preparing', food);
cb(food);
}
function deliverFood(food) {
console.log(food, 'delivered. Have a nice day!');
}
prepareAndDeliverFood( 'milk' , deliverFood );
// closure
function returnGreeting() {
var text = 'Hello, World';
var greetingFunction = function() {
return text;
}
return greetingFunction;
}
var newGreetingFunction = returnGreeting();
console.log( returnGreeting() );
console.log( newGreetingFunction() ); // returns the value of "text"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment