Yup, it does.
In that code sample you are:
- Defining a plain object with some properties
- Using a closure inside one of the properties (a function) to refer to the object you just defined.
I can see that whether you are defining var myWidget
in global scope or inside another function, you will still be traversing up the scope chain to get a reference to myWidget
.
If we use this definition of closures here:
A closure is a combination of a code block and data of
a context in which this code block is created.
Or the mozilla definition:
Closures are functions that refer to independent (free) variables. In other words,
the function defined in the closure 'remembers' the environment in which it was created.
When executing the code block inside myWidget.init()
you are using a closure to refer to myWidget
in the calls to myWidget.left()
and myWidget.right()
as you carry the myWidget
variable in your context/environment (as opposed to finding it locally within the init()
function).
In other words, when you execute myWidget.init()
the following happens:
- Is
myWidget
a local variable inside the current function()
? NO
- Move up to parent scope (ie GLOBAL)
- Is
myWidget
a variable in current (ie GLOBAL) scope? YES --> CLOSURE USAGE
- Ok use this
myWidget
reference to retrieve the variable.
I hadn't ever thought of closures in global scope but it makes perfect sense that scope chaining keeps travelling all the way to up to GLOBAL, which just acts as another function() {}
code block which wraps everything and is the ultimate source for finding the variable we are after, here is another article that supports this view:
http://lostechies.com/derickbailey/2011/11/30/is-javascripts-global-scope-really-just-a-closure/