Yup, he does.
In this code example, you:
- Defining a simple object with some properties
- Using a closure inside one of the properties (functions) to refer to a newly defined object.
I see that if you define var myWidget in the global scope or inside another function, you will still be moving along the scope chain to get a link 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 definition of mozilla :
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 inside myWidget.init() you use the closure to refer to myWidget in the calls to myWidget.left() and myWidget.right() , because you transfer the variable myWidget to your context / environment (as opposed to locating it locally in the function init() ).
In other words, when myWidget.init() is executed, the following happens:
- Is
myWidget local variable inside the current function() ? NO - Move to parent area (i.e. GLOBAL)
- Is
myWidget variable in the current (i.e. global) area? YES β USE OF CLOSING - Use this
myWidget link to get the variable.
I never thought about closing on a global scale, but it makes sense that the chain of chains continues to move to GLOBAL, which just acts as another block of function() {} code that wraps everything and is the final source for finding the variable we follow, here another article that supports this view:
http://lostechies.com/derickbailey/2011/11/30/is-javascripts-global-scope-really-just-a-closure/
source share