I was reading about the Function()
constructor in JavaScript from the link here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
And it mentions the fact that :
Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was created
let count = 0; // var count = 0 works!
function makeCounter() {
let count = 0;
return new Function('return count++;');
}
let counter = makeCounter();
console.log( counter() ); // "ReferenceError: count is not defined
In my example above, isn't the statement let count = 0
above the function makeCounter()
in global scope?
I tried reading about how scoping works and found this Any variable declared outside of a function belongs to the global scope, and is therefore accessible from anywhere in your code
here : https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/
Turns out let count = 0
fits the definition of a global scope but still gives and error!
EDIT : I understand how scoping works, was more concerned about how Function()
works considering it accesses variables from the global scope
as given in definition.