Created
January 16, 2015 18:15
-
-
Save awilson28/2a5e2f80a073ae06b760 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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