On 1/7/11, Dmitry Soshnikov <dmitry.soshni...@gmail.com> wrote:
> On Fri, Jan 7, 2011 at 10:46 AM, Mathias Bynens <math...@qiwi.be> wrote:
>
>>
>>
>> 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?
>>
>>
>>
> While answers above have already clarified the case (yes, a variable in JS
> is declared with using a `var` keyword), I add some notes below.
>
> First, if to nit-pick to technical part, strictly speaking, a variable is
> defined only with using `var` keyword (there is a special section in my old
> article:
> http://dmitrysoshnikov.com/ecmascript/chapter-2-variable-object/#about-variables
> ).
>
> However, if the technical part is not so essential, you may use an
> assignment to an undeclared identifier (your case with foo = 42) for
> creating a property of the global object. The only thing you need in ES3 for
> that is to watch attentively and manage carefully all your variables (to
> avoid collisions with other variables).
>
No, that is not the only thing. Please see the discussion at the URL
from my prev msg: "Checking accidental global variables?"

States:
| But doesn't work in IE because properties in the window or global object
| aren't enumerated in a |for in| loop in IE, and Juriy acknowledged:
| 
http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/22e6b2d147f57ee5/?#dda4dee3390fa71a

And:
| there could be an element with an ID in the
| document and assigning to that will trigger an Error in IE.
-- 
Garrett
> In strict mode of ES5 though, you won't be able to use `foo = 42` case,
> since such assignments are banned and cause a `ReferenceError`. Info:
> http://dmitrysoshnikov.com/ecmascript/es5-chapter-2-strict-mode/#assignment-to-an-undeclared-identifier
>

Not only banned in ES5, but can result in errors in most versions of
IE. Plus it creates the confusion of "where is this identifier
declared?", as mentioned in earlier referenced thread.

> So if you need to define a global property in the some other context, use
> `global.foo = 42`

Yes.

(where `global` refers to the global object). Or via
> `Object.defineProperty(...)`.
Not backwards compatible.

[talk about python]
-- 
Garrett

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/jsmentors@jsmentors.com/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/jsmentors@googlegroups.com/

To unsubscribe from this group, send email to
jsmentors+unsubscr...@googlegroups.com

Reply via email to