3 ms·
No this is a really important question, and it has an answer. They are called closures. They are "environments" in which variables live, each of which can have
by crdrost 6y ago
No this is a really important question, and it has an answer.
They are called closures. They are "environments" in which variables live, each of which can have a parent environment dictated by whatever rules there are. (Some programming languages have it where every use of curly braces creates a sub-environment; in JavaScript originally only the function keyword would introduce a sub-environment and if you write `if (something) { var x = 123; }` then `x` belongs to the parent closure and it might contain `undefined` if the branch was not triggered. Since then JS has introduced let/const which are scoped to curly brackets.)
When you declare a function it still has access to the full space of variables which it was lexically defined with. If you mutate those with one function then another function which has access to that environment can see those changes, etc.
- drchopchop 6y agoGood point, I guess what I was trying to get at is that an object is more equivalent to a closure (function + data i.e. local stack environment) than just a function (which executes with input parameters). The top-voted response put that more eloquently than I did.