JavaScript: how are functions and their scopes/lexical environments passed around? -
i'm playing closure , have no problem understanding how inner functions have access outer lexical environments:
function outer() { var bar = 0; function inner() { console.log(bar); } inner(); } outer(); // prints '0' but gets me this:
function foo() { return function inner() { console.log(bar); } } function outer() { var bar = 0; var fakeinner= foo(); // not same "var fakeinner= function () { console.log(bar); }" fakeinner(); } outer(); // referenceerror: bar not defined here try "define" "inner function" fakeinner assigning function expression returned outside function.
i used think javascript creates fakeinner inside "copy" of code, like: var fakeinner= function () { console.log(bar); }, have access bar, not case -- appears when fakeinner invoked, javascript traces definition. understanding correctly? is, function objects (either declarations or expressions) mere references definition spots, , passing them not change lexical environments (hence inner functions have defined inside explicit syntax)?
yes, functions have access own lexical environment - defined. javascript not have dynamic scope function has kind of access scope called.
this happens attaching scope function object, part of closure.
Comments
Post a Comment