I understand that there is global scope, and additionally nestable functional scope. But are there any other types of scopes or closures in Javascript?
While we’re on the topic, what’s the difference between a scope, and a closure?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A closure is a stack of visible scopes. Let’s say you have the following code:
cis a function that has 4 visible scopes: its own scope (wherev4is defined), thebfunction’s scope (wherev3is defined), theafunction’s scope (wherev2is defined), and the global scope (wherev1is defined). That stack of visible scopes is the closure, and the function is bound to that closure. When the reference to thecfunction is returned up the call chain, frombtoaand finally assigned tof, it carries this closure binding with it, so when you invokef(), it will have access to all those scopes, even though you’re seemingly invoking a function in the global scope. As you see, there are only two kinds of scopes involved — the global scope and the function scope. The main difference is that variables in the global scope are defined as properties of the global object, while function scope vars are not properties of any object and cannot be referenced in any other way but by name. A closure is not a scope in itself, but a collection of scopes.