atom feed4 messages in com.googlegroups.jsmentorsRe: [JSMentors] Namespaces and global...
FromSent OnAttachments
Martin RinehartDec 17, 2010 12:53 pm 
iniminoDec 17, 2010 1:14 pm 
Garrett SmithDec 17, 2010 9:41 pm 
Diego PeriniDec 18, 2010 6:32 am 
Subject:Re: [JSMentors] Namespaces and global variables
From:Garrett Smith ("dht@gmail.com)
Date:Dec 17, 2010 9:41:48 pm
List:com.googlegroups.jsmentors

On 12/17/10, Martin Rinehart <mart@gmail.com> wrote:

Every time I think I know something, JavaScript humbles me. Darn.

I'm doing an application, being very careful to have exactly one global variable: my namespace object. Then I discover this:

var foo = document.createElement( 'whatever' ); foo.id = 'x'

An element `id` must be unique. Choose your IDs carefully, e.g.

foo.id = "previewScroller-currentMovies";

alert( typeof(x) ); // undefined document.body.appendChild( foo ) alert( typeof(x) ); // object alert( x === document.getElementById( 'x' ) ); true

You may see more divergence where the element with the id is in the source code in the HTML. The following should alert "undefined" iff `x` is not a property of the global VO, but if `x` is a property of GlobalScopePolluter and the GlobalScopePolluter is in the prototype of the global object, then I believe the expected result would be to alert the value of `x`, that being that div.

<div id="x"> a</div> <script type="text/javascript"> alert(x); var x; </script>

Browsers may vary in such cases. However, if you are using unique IDs that are unlikely to clash, you won't have such problems.

<div id="orbitAccelerationActuator">...</div>

So my namespace is joined by a global variable for every DOM element that has an id. Ugh. What to do?

That's GLobalScopePolluter, a feature that MSIE developed for IE4. Other browsers copied it. I think it was 1-2 weeks ago on the ML where I explained more about it.

See also: http://perfectionkills.com/understanding-delete/

Good blog post!

See also the blog comments. Those are uncensored, AFAIK, not like some other blogs.

That feature doesn't even work that well in IE, because if you try and assign to `x`, without using var, you'll get a script error.

Choose IDs that are unique in global context, so don't use e.g. `body`, `window`, `form` or any other "unsafe names for form controls". http://www.jibbering.com/faq/names/