“[JavaScript functions] internally store any variables they may refer to that are defined in their enclosing scopes.”
How can I determine what that set of variables is?
For example, David Herman in Effective JavaScript gives this function (and closure):
function sandwichMaker() {
var magicIngredient = "peanut butter";
function make(filling) {
return magicIngredient + " and " + filling;
}
return make;
}
var f = sandwichMaker();
document.writeln("<p>" + f("jelly") + "</p>");
document.writeln("<p>" + f("bananas") + "</p>");
document.writeln("<p>" + f("marshmallows") + "</p>");
Sure, magicIngredient is a variable accessible to make(), but what else is? What if sandwichMaker were itself within a function? And then there are the globals. What is the function looking at when it looks for relevant values within the current scope?
Yes, all the variables from parent functions are accessible (if they are not shadowed). And the highest-scoped function inherits from the global scope then.
You can inspect that with a debugger. Insert a
debugger;statement inmake, and then execute it and have a look into your devtools. You will see something like this:Also have a look at this great article: http://dmitrysoshnikov.com/ecmascript/es5-chapter-3-2-lexical-environments-ecmascript-implementation/
Example view at Chrome Devtools:
(from http://www.briangrinstead.com):