On Jan 7, 8:46 am, 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.
>
> 2) Another option is to use:
>
> window.foo = 42;
>
> 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;
>
you left out one more alternative way to declare a global member:
this.foo = 42;
I usually open my namespace declaration like this so assuming "foo" is
an object:
this || (this.foo = { });
foo.x = ...
and this also work on SpiderMonkey and Rhino.
The advantage of this is that if you load several files augmenting the
primary namespaces each of the file will have the same template:
this || (this.namespace = { });
namespace.method = function {
};
so each required file is virtually independent from the fact that a
specific namespace already exists or has to be created first.
--
Diego
> Let’s assume you’re working in the global scope already and you want
> to create a new global variable. What do you guys recommend? Should
> the `var` keyword be used (first example) even though it’s not
> necessary in this case? Are there any other implications I should be
> aware of? What is considered to be the best practice here?
--
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]