Skip to content

Instantly share code, notes, and snippets.

@awilson28
Created January 16, 2015 18:15
Show Gist options
  • Save awilson28/2a5e2f80a073ae06b760 to your computer and use it in GitHub Desktop.
Save awilson28/2a5e2f80a073ae06b760 to your computer and use it in GitHub Desktop.
//functions can refer to variables defined anywhere in that function's scope chain
function makeSandwich(){
var magicIngredient = 'peanut butter';
//the inner make function refers to magicIngredient, a variable defined in the outer makeSandwich function
function make(filling){
return magicIngredient + ' and ' + filling;
}
return make('jelly');
}
makeSandwich(); // 'peanut butter and jelly'
//functions can refer to variables defined in outer functions even after those outer functions have returned
function sandwichMaker() {
var magicIngredient = 'peanut butter';
function make(filling){
return magicIngredient + ' and ' + filling;
}
return make;
}
var f = sandwichMaker();
f('jelly'); // 'peanut butter and jelly'
//we can make sandwichMaker mroe general:
function sandwichMaker(magicIngredient) {
function make(filling){
return magicIngredient + ' and ' + filling;
}
return make;
}
var turkeyAnd = sandwichMaker('turkey');
turkeyAnd('cheese') // 'turkey and cheese'
turkeyAnd('tomatoes') // 'turkey and tomatoes'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment