On Fri, Jan 7, 2011 at 1:04 AM, dpetroff.sub <[email protected]> wrote:

> On Thu, 6 Jan 2011 23:46:30 -0800 (PST)
> Mathias Bynens <[email protected]> wrote:
>
> > You’re in the global scope, and you want to create a new global var.
> > There are different options. What is the difference between them?
> >
> > 1) This will work because the current scope happens to be the global
> > scope:
> >
> >     var foo = 42;
> >
> > Obviously, this would fail to create the var in the global scope when
> > called from inside another scope.
>
> Yes, it will, but it will be a solution if you want to change the scope
> some time;
>
> >
> > 2) Another option is to use:
> >
> >     window.foo = 42;
> >
>
> That will be good only for browser environments.
>
>
> > This will work regardless of the scope it’s called from.
> >
> > 3) When called from the global scope, you can omit var and just go
> > like this:
> >
> >     foo = 42;
>
> It's not great because if you have many of such definitions it's hard to
> control them.
>
> Also, definitions 2 and 3 look like simple expressions and var keyword
> shows, that
> variable has not been used before.
>
> There is an option to define "global" variable and attach your variables to
> it.
> In this case you could easily change their scope if needed.
>
> E.g.
>
> var global = window;
>
> ...
>
> function someFunc() {
>    global.foo = 'bar';
> }
>
> and later you could just change global to your.private.namespace object.
>
>
> Dmitry Petrov
> --
> dpetroff.sub <[email protected]>
>
> --
> To view archived discussions from the original JSMentors Mailman list:
> http://www.mail-archive.com/[email protected]/
>
> To search via a non-Google archive, visit here:
> http://www.mail-archive.com/[email protected]/
>
> To unsubscribe from this group, send email to
> [email protected]<jsmentors%[email protected]>
>

I generally use "var" whenever I declare a variable in JavaScript to be
consistent. Keeps me from forgetting it later when I'm inside of a different
scope. However, I like the idea of creating a "global" object in the global
scope and attaching variables that I want to be globally available to me. I
may start using that.

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to