Last active
June 11, 2017 22:48
-
-
Save awilson28/0f25c22513f8499ce8ee to your computer and use it in GitHub Desktop.
Examples of closure courtesy of Effective JavaScript by David Herman
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
//examples courtesy of Effective JavaScript by David Herman | |
//functions can refer to variables defined anywhere in that function's scope chain | |
function makeSandwich(){ | |
var magicIngredient = 'peanut butter'; | |
function make(filling){ | |
return magicIngredient + ' and ' + filling; | |
} | |
return make('jelly'); | |
} | |
makeSandwich(); // 'peanut butter and jelly' | |
/* | |
Here's what's happening above: | |
the inner make function refers to magicIngredient, a variable | |
defined in the outer makeSandwich function. When makeSandwich is | |
invoked on line 14, it returns the inner make function | |
*/ | |
//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 more 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