Tuesday, January 17, 2017

functions & their own lexical environment

function foo() {
  return function inner() {
    console.log(bar);
  }
}
function outer() {
  var bar = 0;
  var fakeInner= foo();  
  // not the same as "var fakeInner= function () { console.log(bar); }"
  fakeInner();
}
outer(); // ReferenceError: bar is not defined 
Functions do only have access to their own lexical environment - from where they were defined. JavaScript does not have dynamic scope where a function has any kind of access to the scope where it is called.
This happens by attaching the scope to the function object, it is a part of the closure.
@reference_1_stackoverflow
@reference_2_wikipedia
@reference_3_ stackoverflow

No comments:

Post a Comment