Functions in Javascript run in the scope they are defined, not in the scope they are executed.
var baz;
(function() {
baz = function() {
return foo * bar;
};
var foo = 20;
var bar = 2;
})();
console.error(baz());
//output: 40
I will be posting tricks I have been using in my journey.
So follow me on LinkedIn.
Top comments (1)
Not 100% true. If you create a function using the
new Function(...)
syntax (which is rare and unusual) - they are actually attached to the global scope, and not the scope in which they were defined.