On Oct 26, 4:29 am, ociardhp <paul.p.ca...@gmail.com> wrote:
> Hi
>
> I've seen some code similar to the following and would like to confirm
> my understanding. I assume the object literal created in the return
> has access to the enclosing scope which includes the variable age,
> effectively creating a closure over it when created, and that this is
> what enables the assignment to moon.age?
No (see below).
> Is this considered good style
> and is there any particular reason for using that approach as opposed
> to the clearer (in my opinion) declaration of age within the object
> literal?
The pattern is used to emulate the behaviour of private variables that
can be read or set by priveliged functions:
<URL:
http://www.crockford.com/javascript/private.html >
[...]
> <script>
> moon = function() {
> var age;
This variable is local to the anonymous function assigned to moon. It
can't be directly accessed from outside the function.
>
> return {
> // age: 4000000000,
Had you not commented out that line, the object returned by the
function and assigned to moon would have an age property with a value
of 4000000000. It is a different thing to the local age variable
declared earlier - they both exist independently.
> showDarkSide: function() {
> return false;
> }
This function has access to the activation object created by executing
the "outer" anonymous function, so you could make it a priveliged
function that gets or sets the value of the private age variable. It
can also modify the public moon.age property.
> }
> }();
>
> moon.age = 42;
Here you create a property of moon called age (if it doesn't already
exist) and assign it a value of 42.
--
Rob