问题
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?
回答1:
A closure is a stack of visible scopes. Let's say you have the following code:
var v1;
function a() {
var v2;
function b() {
var v3;
function c() {
var v4;
}
return c;
}
return b();
}
var f = a();
c
is a function that has 4 visible scopes: its own scope (where v4
is defined), the b
function's scope (where v3
is defined), the a
function's scope (where v2
is defined), and the global scope (where v1
is defined). That stack of visible scopes is the closure, and the function is bound to that closure. When the reference to the c
function is returned up the call chain, from b
to a
and finally assigned to f
, it carries this closure binding with it, so when you invoke f()
, 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.
来源:https://stackoverflow.com/questions/12543395/what-types-of-scope-exist-in-javascript