3 ms·
Closures are simpler than that. All that a closure does is capture an enclosing environment, and then be able to refer to variables from it later. All of the
by btilly 13y ago
Closures are simpler than that. All that a closure does is capture an enclosing environment, and then be able to refer to variables from it later.
All of the confusion in JavaScript comes from the fact that the enclosing environment is generally bound to the nearest function call. This is not what people expect, and it is not what happens in other languages with closures.
If versioning JavaScript features was not such a mess, it wouldn't happen in JavaScript either. Everyone would learn to declare variables with let instead of var, and closures would just work sanely. Unfortunately you need to use JavaScript 1.7 to get that feature, and browsers assume that you're using JavaScript 1.5 unless you jump through hoops to get there.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7 https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_... for more.
- christian_fei 13y agoi came to the conclusion that functions === closures. closure/functions close the parents scoped variables in an own scope
- btilly 13y agoThat conclusion is language dependent. When you learn other languages, you'll encounter ones like eLisp and C++ which have equivalents of anonymous functions, without making them closures.
- christian_fei 13y agook. but at least in javascript this mysterious phrase is true, right?
- btilly 13y agoYes. But it is one of a set of mysterious phrases like "pass by value" and "pass by reference" which, if you learn them, will make it much easier to keep multiple languages in your head.