By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,496 Members | 1,489 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,496 IT Pros & Developers. It's quick & easy.

window object

P: n/a
yb
Hi,

Is there a standard for the global 'window' object in browsers? For
example, it supports methods such as setInterval and clearInterval, and
several others.

I know that w3c standardized several parts of the DOM, but this does
not include the window object.

Thank you

Mar 2 '06 #1
Share this Question
Share on Google+
26 Replies


P: n/a
yb wrote:
Hi,

Is there a standard for the global 'window' object in browsers? For
example, it supports methods such as setInterval and clearInterval, and
several others.
The window object is not part of either the ECMAScript Language or W3C
Document Object Model (DOM) specification - it belongs to DOM Level 0,
which is described in the introduction to the W3C DOM 1 specification as:

'The term "DOM Level 0" refers to a mix (not formally specified)
of HTML document functionalities offered by Netscape Navigator
version 3.0 and Microsoft Internet Explorer version 3.0. In some
cases, attributes or methods have been included for reasons of
backward compatibility with "DOM Level 0".'

<URL:http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html#ID-1176245063>
You will find references to the window object in the Gecko DOM reference:
<URL:http://developer.mozilla.org/en/docs/DOM:window>

and MSDN's 'HTML and DHTML' documentation:
<URL:http://msdn.microsoft.com/workshop/author/dhtml/reference/objects/obj_window.asp>
The global object is a concept of the ECMAScript Language (colloquially
known as 'JavaScript', which is a registered trademark of Sun
Microsystems, Inc.), see section 10.1.5 of the specification.

In user agents that have a concept of a window object, it is synonymous
with the global object. When explaining the global object, the above
reference says:

"...in the HTML document object model the window property of
the global object is the global object itself."
You can test whether that is true - 'this' outside any other context
refers to the global object:

var Global = this;

Now 'Global' refers to the global object. To check that it refers to
the same object as window:

alert( Global === window ); // shows 'true'
I guess it's possible that somewhere there is an ECMAScript environment
that implements a window object that isn't the global object. It's more
likely you'll find one that doesn't have a window object at all (but it
must have a global object if compliance matters).

I know that w3c standardized several parts of the DOM, but this does
not include the window object.


Generally there is no need to reference the window object. If there is
a circumstance that you feel 'window' should be included in a reference,
but are uncertain whether the environment supports a window object, then
use the abovementioned 'Global' variable, e.g.

var Global = this;

function someFn(){
...
Global.setTimeout(...);
...
}
Some believe that a fully qualified reference (e.g. window.setTimeout())
makes scripts run faster as it reduces the time spent on scope chain
resolution - I have never tried to confirm whether that is true or not.
--
Rob
Mar 3 '06 #2

P: n/a
RobG <rg***@iinet.net.au> writes:
I guess it's possible that somewhere there is an ECMAScript
environment that implements a window object that isn't the global
object.
The Adobe SVG plugin, IIRC.
It has a window object, but it is not the global object.

Also note that the SVG specification is trying to formalize
some parts of DOM 0.
Some believe that a fully qualified reference
(e.g. window.setTimeout()) makes scripts run faster as it reduces the
time spent on scope chain resolution - I have never tried to confirm
whether that is true or not.


It should be false. In fact is should run slower, if anything.
The global "window" variable name is no different form "setTimeout".
Both must be looked up in the same scope chain, ending at the global
object. After that, "window.setTimeout" will do one further property
lookup on the global object, so it should take longer than just using
"setTimeout" directly.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Mar 3 '06 #3

P: n/a
VK

Lasse Reichstein Nielsen wrote:
It should be false. In fact is should run slower, if anything.
The global "window" variable name is no different form "setTimeout".
Both must be looked up in the same scope chain, ending at the global
object. After that, "window.setTimeout" will do one further property
lookup on the global object, so it should take longer than just using
"setTimeout" directly.


It is not true at least for IE 5.0 or higher and Opera 8.0 or higher -
thus for 80%-90% of the browsers on the market (grace to IE). Therefore
ECMA-compliant scope schema will be rather a rare exeption than a rule
with your visitors. One can hate it, scream and cry about it :-) - but
at least she should be aware of it.

For IE and Opera "Global" object and "window" object constitute two
distinct programming scopes. Again I'm not talking about some
occasional models like Adobe SVG plugin or such.
I'm talking about the standard environment of a HTML page (XHTML is not
supported by IE and interpreted as regular HTML) with a script running
on it.

In such case we have Global scope (level of global variables ang Global
methods like escape, encodeURI etc.) and Window scope *above* it (level
of ID'entified HTML elements and window methods like setTimeout, open
etc.)

On lookup the engine search first in the Global scope, if not found
then in the window scope.

Therefore if we say declare
var setTimeout = 'foobar';
we shadow window.setTimeout reference (engine will find "setTimeout" in
the Global scope first thus will never look in the window scope above).

Respectively if we declare:
window['foo'] = 'bar';
and later call alert(foo) then
engine will look first in the Global scope, fail on it, then look in
the window scope and find it.

For a non-aware user the fact that:
window['foo'] = 'bar';
alert(foo); // 'bar'
may lead to the conclusion that Global scope and window scope are the
same - but nothing more far from the true than that, again - at least
for IE and Opera.

It also explain the real mechanics of possible circular reference leaks
in IE as well as explains the overall higher memory consumption by
JScript - which is *not* a memory leak but makes nervious many
developers, specially ones coming from a C++ or so background.

As I'm kind of tired of regular hysterics about "VK unbellyfeels ECMA":
here a sample and I don't care if it trigs the thinking process or the
doublethink will help as usual.
....
<script type="text/javascript">
var v1 = true;

function demo() {
var v2 = true;
alert(v1);
alert(v2);
alert(this[v2]);
alert(v3);
}

window.onload = demo;
</script>
....
<div id="v1">v1</div>
<div id="v2">v2</div>
<div id="v3">v3</div>
....

P.S. If it helped to start the thinking process (which I still hope
despite don't care too much anymore):- the next question would be: "Is
it possible and how in IE's scope model that a DOM object is still
referenced in the execution context - thus not GC-available - despite
no one JScript variable holds a reference to it?"

Mar 3 '06 #4

P: n/a
RobG wrote:
[...]
The global object is a concept of the ECMAScript Language (colloquially
known as 'JavaScript', which is a registered trademark of Sun
Microsystems, Inc.), see section 10.1.5 of the specification.

In user agents that have a concept of a window object, it is synonymous
with the global object. When explaining the global object, the above
reference says:

"...in the HTML document object model the window property of
the global object is the global object itself."
However, this is not a normative statement.

You have already pointed out that "the window object" is not specified in
ECMAScript or the W3C DOM. But to be absolutely clear about this: The
above non-normative statement originates from ECMAScript Edition 1 (June
1997) where it referred to "(the) HTML (document object model)" of the
only user agents that implemented ECMAScript: Netscape Navigator (with
JavaScript), and Internet Explorer (with JScript). (Most notably, in
JavaScript there had been no separation between core language and
[Netscape] DOM/AOM before JavaScript 1.4 [1999].) It certainly was not
intended to refer to the W3C Document Object Model HTML specifications
(the earliest draft of W3C DOM Level 1 HTML dated 1997-10-09). The term
"HTML" has been changed to "the HTML document object model" in ECMAScript
Edition 3 (December 1999), probably to distinguish between the markup
language and the object model used to access the element tree created
when it is parsed.
You can test whether that is true - 'this' outside any other context
refers to the global object:

var Global = this;

Now 'Global' refers to the global object. To check that it refers to
the same object as window:

alert( Global === window ); // shows 'true'


Your logic is flawed, because the `window' property of the Global object
refers to a host object which does not need to strictly implement
ECMAScript algorithms, including the algorithm for the `===' operator.

Given the above strict comparison, it could as well be, and would strictly
conform to the ECMAScript specification, that the Global Object and the
object referred to by its host-defined `window' property are different
objects; that the properties of the object referred to by the `window'
property of the Global Object are also host-defined properties of the
Global object that are added to it before execution context is entered;
that every augmentation of the host object referred to with the `window'
property of the Global Object includes augmentation of the Global Object
(and vice-versa) through language-specific conforming extensions to the
ECMAScript specification. It has been showed already here that there is a
host object that implements the `==' operation different than specified.
PointedEars
Mar 3 '06 #5

P: n/a
VK

RobG wrote:
In user agents that have a concept of a window object, it is synonymous
with the global object.
I'm aware of only one browser where this is true: Firefox. "Bravo
Firefox!" etc. but with the current share of actions this standard
behavior is rather non-standard on the web-wide run.
When explaining the global object, the above
reference says:

"...in the HTML document object model the window property of
the global object is the global object itself."
While MSDN says: "For client versions of JScript, this refers to the
window object if used outside of the context of any other object."
However non-standard it may be, it is implemented exactly as
documented.

You can test whether that is true - 'this' outside any other context
refers to the global object:

var Global = this;

Now 'Global' refers to the global object. To check that it refers to
the same object as window:

alert( Global === window ); // shows 'true'


Again: this test does what expected only for Firefox. In IE you simply
getting a reference to the window and then compare window===window with
is naturally true. Global object is escaping this test. See my post in
this thread for the correct test demonstrating that Global and Window
are different objects with separate scopes.
Moreover IE distincts "The Window" (the global context atop of Global
object) and "the window" (surrent window where the script is
executing). Therefore "window" object is "The Window" while window.self
is "the window". IE needs it as it implements additional current window
scope for constructors. Say you cannot create a new instance using
constructor located in another frame (it will be "Cannot use freed
script" error).

Overall there is much more of mechanics here than one sencence from
Books of ECMA. And actually Books of ECMA is the least informative
source to look at *for this particular question*. ;-)

Just another chunk to think about (feel free to experiment further)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN"
"http://www.w3.org/TR/html401/strict.dtd">
<html>
<head>
<title>Global vs. Window</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">

<style type="text/css">
body { background-color: #FFFFFF}
</style>

<script type="text/javascript">
/* Test 1 */
alert(this === window);
alert(this === window.window);
alert(this === self);
alert(window === self);

// IE 6.0
// true
// false
// false
// false

// Opera 8.51
// false
// false
// false
// true

// Firefox 1.5.0.1
// true
// true
// true
// true

function demo() {
/* Test 2 */
var alert = function(m) {window.alert(m+'bar');}
alert('foo'); // 'foobar'
window.alert('foo'); // 'foo'
}

window.onload = demo;
</script>

</head>

<body>

<div id="v1">v1</div>
<div id="v2">v2</div>
<div id="v3">v3</div>

</body>
</html>

Mar 4 '06 #6

P: n/a
VK
> >RobG wrote:
In user agents that have a concept of a window object, it is synonymous
with the global object.
VK wrote:
I'm aware of only one browser where this is true: Firefox.


Actually it is not true for Firefox neither: they just tryed to *mimic*
that ECMA statement as hard as they could, so it's really difficult to
catch them on the act :-)

Nevertheless the test #2 from my previous post gets them - I just
didn't check it first on Firefox:

function demo() {
/* Test 2 */
var alert = function(m) {window.alert(m+'bar');}
alert('foo'); // 'foobar'
window.alert('foo'); // 'foo'
// Gocha! :-)
}

Mar 4 '06 #7

P: n/a
On 04/03/2006 14:12, VK wrote:
function demo() {
/* Test 2 */
var alert = function(m) {window.alert(m+'bar');}
alert('foo'); // 'foobar'
window.alert('foo'); // 'foo'
// Gocha! :-)
}


That doesn't prove anything, except that /you/ are unbelievably incompetent.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Mar 4 '06 #8

P: n/a
VK

Michael Winter wrote:
On 04/03/2006 14:12, VK wrote:
function demo() {
/* Test 2 */
var alert = function(m) {window.alert(m+'bar');}
alert('foo'); // 'foobar'
window.alert('foo'); // 'foo'
// Gocha! :-)
}


That doesn't prove anything, except that /you/ are unbelievably incompetent.


As I said: whatever.

P.S.
<script type="text/javascript">
var alert = function(m){window.alert('bar');}
(this.alert('foo'));

// 'foo'
// 'bar'
</script>

Mar 4 '06 #9

P: n/a
VK wrote:
Michael Winter wrote:
On 04/03/2006 14:12, VK wrote:
> function demo() {
> /* Test 2 */
> var alert = function(m) {window.alert(m+'bar');}
> alert('foo'); // 'foobar'
> window.alert('foo'); // 'foo'
> // Gocha! :-)
> }


That doesn't prove anything, except that /you/ are unbelievably <-.
incompetent. |

|
As I said: whatever. |
|
P.S. |
<script type="text/javascript"> |
var alert = function(m){window.alert('bar');} |
(this.alert('foo')); |
|
// 'foo' |
// 'bar' |
</script> |

|
---------------------------------------------------------------------'
PointedEars
Mar 4 '06 #10

P: n/a
On 04/03/2006 15:44, VK wrote:
Michael Winter wrote:
[snip]
That doesn't prove anything, except that /you/ are unbelievably
incompetent.


As I said: whatever.


The fact that you don't understand your own code is proof.
P.S.
<script type="text/javascript">
var alert = function(m){window.alert('bar');}
(this.alert('foo'));


This is more interesting, but not for the reason you'd like to think.

It seems that Fx isn't parsing this properly. The following:

var alert = function() {
window.alert('bar');
};
(this.alert('foo'));

should be exactly identical; the only significant difference is the
addition of a semicolon at the end of the variable declaration. However,
the change in behaviour is profound: instead of the previous two
dialogue boxes, the code now throws a recursion error.

It seems that the previous code (posted by VK) is equivalent to:

var alert = (function() {
window.alert('bar');
})(this.alert('foo'));

That is, the native alert method is called with an argument, 'foo'. The
return value (undefined) is then passed as an argument to a function
expression, which calls the native alert method a second time, with an
argument, 'bar'. The return value from the function expression call
(undefined) is then assigned to declared variable, alert. This final
step can be observed in both cases with a call to the write method:

document.write(typeof alert); /* undefined */
To Randy (if you're reading): I think you asked for an example where
explicit semicolons make a difference. This is a bug, granted, but an
example nevertheless. :)

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Mar 4 '06 #11

P: n/a
On 04/03/2006 16:27, Michael Winter wrote:
On 04/03/2006 15:44, VK wrote:
[snip]
var alert = function(m){window.alert('bar');}
(this.alert('foo'));


[snip]
var alert = function() {
window.alert('bar');
};
(this.alert('foo'));

should be exactly identical [...]


I forgot to mention that removing the parentheses from around the call
(preceding semicolon, or not) also produces the expected recursion error.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Mar 4 '06 #12

P: n/a
On 04/03/2006 16:27, Michael Winter wrote:
On 04/03/2006 15:44, VK wrote:
Michael Winter wrote:

[snip]
That doesn't prove anything, except that /you/ are unbelievably
incompetent.

As I said: whatever.

The fact that you don't understand your own code is proof.
P.S.
<script type="text/javascript">
var alert = function(m){window.alert('bar');}
(this.alert('foo'));


[snip]
It seems that Fx isn't parsing this properly. [...]


Scratch that. I'm so used to writing:

(function() {
})(...);

that I forgot that:

function() {
}(...);

is perfectly fine as long as 'function' isn't the first token (as in the
Initialiser production, above).

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Mar 4 '06 #13

P: n/a
VK
Michael Winter wrote:
The fact that you don't understand your own code is proof.


I don't understand ECMA/Firefox sometimes - it is true. Their way of
thinking and acting is sometimes too alien to what I used from Netscape
and Internet Explorer.

So I just have to repeat once again: "Bravo Firefox!". Whatever is
strictly spelled, vaguely mentioned or softly murmured in ECMA or W3C
is being implemented at the best of human abilities.

So then we have two scope schemas: one from IE other from FF. Opera is
kind of sitting between two chairs (which is the normal position for
this browser :-)

I'm wandering what my tests would show for Safari/Konqueror.

Mar 4 '06 #14

P: n/a
VK wrote:
Michael Winter wrote:
> The fact that you don't understand your own code is proof.

I don't understand ECMA/Firefox sometimes - it is true.


You have never displayed a blink of understanding of the specification.
Their way of thinking and acting is sometimes too alien to what I used
from Netscape and Internet Explorer.


It is not. You have just still not understood that Netscape 3+ and Internet
Explorer use ECMAScript implementations as primary scripting language, and
that conforming ECMAScript implementations may be extended compared to the
specification, according to its Conformance section.
PointedEars
Mar 4 '06 #15

P: n/a
VK

Thomas 'PointedEars' Lahn wrote:
It is not. You have just still not understood that Netscape 3+ and Internet
Explorer use ECMAScript implementations as primary scripting language
One cannot implement something that has to be written yet (ECMAScript
specs).
Netscape Gold and Internet Explorer 3.02 simply have JavaScript 1.1 and
JScript 1.0 as primary scripting language respectively (Internet
Explorer 3.0 has VBScript as default language).
and
that conforming ECMAScript implementations may be extended compared to the
specification, according to its Conformance section.


What does it have to do with tea and China? IE and Opera have two
separate scopes: Global and enclosing Window. Firefox has (or
pretending to have) only one: Global wich is Window (or Window which is
Global - I'm really lost here). If both allowed by specs so the better.
If one of them is not allowed by specs - it doesn't make it disappear.

One cannot just keep saying "This is so because it is written so". You
need some correlation with the reality, especially if it involves
80%-90% of UA's (?)

Mar 4 '06 #16

P: n/a
VK wrote:
Thomas 'PointedEars' Lahn wrote:
It is not. You have just still not understood that Netscape 3+ and
Internet Explorer use ECMAScript implementations as primary scripting
language
One cannot implement something that has to be written yet (ECMAScript
specs).


One can. It is the idea of the language that counts here, not the written
representation of it.
Netscape Gold and Internet Explorer 3.02 simply have JavaScript 1.1 and
JScript 1.0 as primary scripting language respectively
,-[ECMAScript Edition 3]
|
| Brief History
|
| This ECMA Standard is based on several originating technologies, the
| most well known being JavaScript (Netscape) and JScript (Microsoft). The
| language was invented by Brendan Eich at Netscape and first appeared in
| that company's Navigator 2.0 browser. It has appeared in all subsequent
| browsers from Netscape and in all browsers from Microsoft starting with
| Internet Explorer 3.0.
|
| The development of this Standard started in November 1996. The first
| edition of this ECMA Standard was adopted by the ECMA General Assembly
| of June 1997.
|
| That ECMA Standard was submitted to ISO/IEC JTC 1 for adoption under the
| fast-track procedure, and approved as international standard ISO/IEC
| 16262, in April 1998. The ECMA General Assembly of June 1998 approved the
| second edition of ECMA-262 to keep it fully aligned with ISO/IEC 16262.
| Changes between the first and the second edition are editorial in nature.

Therefore, and because of the behavior they display, one can say
rightfully that both JavaScript 1.1 (implemented in Netscape 3.0,
August 1996), and JScript 1.0 (implemented in IE 3.0, dito) are
(extended) ECMAScript implementations.
(Internet Explorer 3.0 has VBScript as default language).


I cannot test that, yet both the W3C DOM HTML Specification (in
its reference to DOM Level 0) and the MSDN Library say otherwise.
PointedEars
Mar 4 '06 #17

P: n/a
VK wrote:
Lasse Reichstein Nielsen wrote:
It should be false. In fact is should run slower, if anything.
The global "window" variable name is no different form
"setTimeout". Both must be looked up in the same scope chain,
ending at the global object. After that, "window.setTimeout"
will do one further property lookup on the global object, so
it should take longer than just using "setTimeout" directly.
It is not true at least for IE 5.0 or higher and Opera 8.0
or higher - thus for 80%-90% of the browsers on the market
(grace to IE).


What is not true? That - window.setTimeout - should take longer to
resolve than unqualified - setTimeout -? It does take longer, you just
have to time it to see that.
Therefore ECMA-compliant scope schema will be rather a rare
exeption than a rule with your visitors. One can hate it,
scream and cry about it :-) - but at least she should be
aware of it.
So is it the resolution of Identifiers against the scope chain, or the
scope chain itself that you think does not follow the specification?
That should be fairly simple to demonstrate as all you would have to do
is show some code that ECMA 262 says should result in one behaviour that
actually exhibits another. Of course you need to both know what ECMA 262
says the code should do and understand the code written. That is a bit
of a problem for you as you don't understand ECMA 262 or the javascript
you write.
For IE and Opera "Global" object and "window" object
constitute two distinct programming scopes. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

And that should be a fairly simple assertion to back-up. Although
"programming scopes" is essentially meaningless; another piece of
fictitious jargon from someone more interested in giving the impression
that they know more than they do. On the other hand "two distinct" is
concrete enough for consideration. It implies that the global object and
the window object are two distinct entities.
Again I'm not talking about some
occasional models like Adobe SVG plugin or such.
I'm talking about the standard environment of a HTML page
(XHTML is not supported by IE and interpreted as regular HTML)
with a script running on it.

In such case we have Global scope (level of global variables
ang Global methods like escape, encodeURI etc.) and Window scope
*above* it (level of ID'entified HTML elements and window methods
like setTimeout, open etc.)
The implication if which is that there are two distinct objects on the
scope chain; one the ECMAScript global object with the specification
defined properties and the other a true host object with browser defined
properties.
On lookup the engine search first in the Global scope, if not
found then in the window scope.
So in scope chain resolution the ECMAScript global object is encountered
first on the scope chain and the 'window' object comes after that?

Well, we can test that proposition with a bit of scope chain
augmentation. Suppose we explicitly put the object referred to by -
window - on the scope chain of an inner function (with a - with -
statement) and give the outer function local variables with identifiers
that would mask global properties of interest. Acting upon those
unqualified Identifiers inside the inner function would not involve the
consequences of getting to the end of the scope chain because if not
resolved as propitious of the object added to the scope chain they would
be caught by being resolved as priorities of the Activation/variable
object of the outer function.

If the window and global objects are two distinct entities that have
different sets of properties, Identifiers referring to properties of
the one that had _not_ been added to the scope chain would be
resolved as the outer function's local variables. Finding any single
Identifier that could not be resolved as a property of the object
added to the scope chain would _prove_ that there were two distinct
objects, failing to demonstrate this would suggest a single global
object. E.G:-

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/javascript">

var globalVar = 'Global Variable';

function getWindow(){
return window;
}
function getGlobal(){
return this;
}

window.onload = (function(){
var localFnc;
/* Identifier corresponding with IDed DIV element */
var testDiv = 'Outer Function variable';

/* Identifiers corresponding with ECMA global object properties */
var Math = 'Outer Function variable';
var Array = 'Outer Function variable';
var Object = 'Outer Function variable';
var eval = 'Outer Function variable';
/* Identifiers corresponding with browser object model global
properties. */
var clipboardData = 'Outer Function variable';
var setTimeout = 'Outer Function variable';
var alert = 'Outer Function variable';
var window = 'Outer Function variable';

/* Identifier corresponding with a declared global variable */
var globalVar = 'Outer Function variable';

/* Explicitly add a property to the - window - object:- */
getWindow()['foo'] = 'Assigned to window object'
/* Identifier corresponding with an property explicitly added
to the window object */
var foo = 'Outer Function variable';

/* Explicitly add a property to the - this - object:- */
this['bar'] = 'Assigned to window object'
/* Identifier corresponding with an property explicitly added
to the window object */
var bar = 'Outer Function variable';

/* Cannot use the - window - reference directly as it is defined
as a local string variable in this scope so call a function
that will return - window - instead:- */
with( getWindow() ){ // Add the - window - object to the inner
// function's scope chain.
localFnc = (function(){
alert(
'*Identifier corresponding with IDed DIV element\n'+
'testDiv = '+testDiv+

'\n\n*Identifiers corresponding with ECMA global object'+
' properties\n'+
'\nMath = '+Math+
'\nArray = '+Array+
'\nObject = '+Object+
'\neval = '+eval+

'\n\n*Identifiers corresponding with browser object model'+
' global properties.\n'+
'\nclipboardData = '+clipboardData+
'\nsetTimout = '+setTimeout+
'\nalert = '+alert+
'\nwindow = '+window+

'\n\n*Identifier corresponding with a declared global'+
' variable\n'+
'\nglobalVar = '+globalVar+

'\n\n*Identifier corresponding with an property explicitly'+
' added to the window object'+
'\nfoo = '+foo+

'\n\n*Identifier corresponding with an property explicitly'+
' added to the global - this - object'+
'\nbar = '+bar+
''
);
});
}
/* Return the inner function so it can be assigned to
- window.onload -:- */
return localFnc;
})();
</script>
</head>
<body>
<div id="testDiv">XXX</div>
</body>
</html>

It is also possible to repeat that experiment using the - this -
reference as the object added to the scope chain (or any other
candidate for similar consideration).

And the results of running that on IE 6 are that whichever object (-
window - or - this -) is added to the inner function's scope chain that
object has; properties that correspond with IDed DOM elements,
properties that correspond with ECMA 262 defined global properties,
properties that correspond with expected browser object model global
properties, properties that correspond with declared global variables
and properties corresponding with properties added to both the -
window - and - this - object at runtime.

This result shows no evidence of two distinct objects at the end of the
scope chain as the single object that is expected to be at the end of
the scope chain behaves as if it has all the required properties itself.
Therefore if we say declare
var setTimeout = 'foobar';
we shadow window.setTimeout reference (engine will find
"setTimeout" in the Global scope first thus will never
look in the window scope above).
No demonstration of 'shadowing' has been made. The behaviour
demonstrated is instead completely in accordance with a single global
object being subject to procedure for variable instantiation as
described in ECMA 262, 3rd ed. sections 10.1.3 and 10.2.1.
Respectively if we declare:
window['foo'] = 'bar';
and later call alert(foo) then engine will look first in
the Global scope, fail on it, then look in
the window scope and find it.
With the implication that the global object does not have an - alert -
property or a - foo - property? Neither have been demonstrated, and the
above test shows that both the - window - object and the global - this -
object behave in isolation as if they have properties corresponding with
ECMA 262 defined global properties, browser global properties, declared
local variables, runtime added properties, etc.
For a non-aware user the fact that:
window['foo'] = 'bar';
alert(foo); // 'bar'
may lead to the conclusion that Global scope and window scope
are the same - but nothing more far from the true than that,
again - at least for IE and Opera.
So far no case has been made for that conclusion.
It also explain the real mechanics of possible circular
reference leaks in IE
You mean the things that you didn't believe existed last week, and still
don't understand?
as well as explains the overall higher memory consumption
by JScript - which is *not* a memory leak but makes nervious
many developers, specially ones coming from a C++ or so
background.
Explaining the circular reference memory leaks in terms of inaccessible
additional objects in the scope chain would be inadequate as then the
problem could not be addressed, due to the inaccessibility of these
additional objects.
As I'm kind of tired of regular hysterics about
"VK unbellyfeels ECMA":
Stop making out that you know something special to people who have a
better understanding of the subject than you and have considerably
greater talent for analysis than you and you may stop people calling you
a fool.
here a sample and I don't care if it trigs the thinking
process or the doublethink will help as usual.
Although writing sentences that make sense would also contribute to your
not being considered quite the fool you currently are.
...
<script type="text/javascript">
Once again you post code without stating what it is you suppose that it
is demonstrating. And in not stating what is supposed to be demonstrated
by this code it becomes difficult to say whether it is demonstrated or
not, but presumably if you are trying to make any point at all your
notion of this code is that it demonstrates something that would differ
from the behaviour predicted by an ECMA 262 conforming implementation.
Well, lets look at the ECMA 262 derived perdition and see if the results
do demonstrate IE differing from that behaviour:-
var v1 = true;
A global variable is declare and assigned a value. Variable
instantiation in the global scope uses the ECMAScript global object as
the variable object so it would be the global object to which a property
would be added with the name 'v1', unless the property already exists in
which case it is left alone. When the global code is executed a value is
assigned to that property of the global object.
function demo() {
var v2 = true;
A local variable is created with the name 'v2' on the function's
execution context's Activation/variable object and when the function
body is executed the boolean value - true - is assigned to that
property.
alert(v1);
Output, now we get to see if behaviour corresponds with expectations.
The Identifier - alert - is resolved into a reference to the global -
alert - function and that function is called with an argument list
consisting of the value read using the Identifier - v1 - . The
Identifier - v1 - is resolved at the end of the scope chain as a
property of the global object that corresponds with the declared global
variable and has the value - true -. The - alert - function
type-converts its boolean - true - argument into the string 'true' and
alerts that.

ECMA 262 predicted outcome: alters the string 'true'.

Observed outcome: alerts the string 'true'.
alert(v2);
Similarly the Identifier - v2 - is resolved as a property of the
function's execution context's Activation/Variable object. That property
has the value - true - and alert type converts that into the string
'true'.

ECMA 262 predicted outcome: alters the string 'true'.

Observed outcome: alerts the string 'true'.
alert(this[v2]);
This time the argument to - alert - is the result of the expression -
this[v2] -. As this function is executed as a method of the - window -
object the - this - keyword is resolved as a reference to the - window -
object. The bracket notation property accessor requires that the - v2 -
Identifier be resolved, evaluated and type-converted into a string that
will be used as a property name in association with the - this - object.
The - v2 - Identifier is resolved as the local variable - v2 - with the
value - true -. That value is type-converted into the string 'true' and
used as the property name to be resolved in association with - this -,
i.e.- this['true'] -.

The expression - this['true'] - returns the value - undefined - because
the window object has no property named 'true', and alert type-converts
undefined into the string 'undefined' and alerts that.

ECMA 262 predicted outcome: alters the string 'undefined'.

Observed outcome: alerts the string 'undefined'.
alert(v3);
As we know IE (and other browsers) make DOM elements with ID attributes
available as global properties under names corresponding with their IDs,
assuming that they do not clash with declared global variables. The
Identifier - v3 - corresponds with the ID of a DOM element and does not
clash with a declared global variable so we can expect - v3 - to resolve
as a reference to that DOM element. The type-conversion of an IE DOM
element to a string is the string '[object]' so that is what will be
alerted.

ECMA 262 predicted outcome: alters the string '[object]'.

Observed outcome: alerts the string '[object]'.
}

window.onload = demo;
</script>
...
<div id="v1">v1</div>
<div id="v2">v2</div>
<div id="v3">v3</div>
...
So once again you post code that is supposed to demonstrate some arcane
'truth' that actually does no more than behave 100% in accordance with
the behaviour that would be expected of a 100% ECMA 262 3rd ed.
conforming implementation. There is certainly nothing happening here
that requires more than one global object, or suggests any additional
objects on the scope chain.

Did you, by any chance, let yourself be fooled by - alert(this[v2]); -
alerting ' undefined'? I think you did, but as has been pointed out so
many times you don't understand the basics of javascript so you don't
understand what the code you write actually does. You probably indented
to write - alert(this['v2']); - or - alert(this.v2); -, but that would
have alerted '[object]' and done nothing but demonstrated more expected
behaviour.
P.S. If it helped to start the thinking process (which
I still hope despite don't care too much anymore):-
It appears that no matter how often you make yourself look a fool in
public it never starts your thinking process. You have made the mistake
of confusing yourself with someone who knows what they are doing and
apparently no amount of evidence to the contrary is capable of enabling
you to rectify that error.
the next question would be: "Is it possible and how in IE's
scope model that a DOM object is still referenced in the
execution context - thus not GC-available - despite
no one JScript variable holds a reference to it?"


Given that you made your original proposition up off the top of your
head without any evidence to back it up and posted a non-demonstration
of it 'in action', the 'next question' is entirely moot. However, that
'next question' hardly qualifies as a question, being the sort of
incoherent rambling that might be expected from the mentally ill.

Richard.
Mar 4 '06 #18

P: n/a
Thomas 'PointedEars' Lahn said the following on 3/4/2006 3:20 PM:
VK wrote:


<snip>
(Internet Explorer 3.0 has VBScript as default language).


I cannot test that, yet both the W3C DOM HTML Specification (in
its reference to DOM Level 0) and the MSDN Library say otherwise.


And those two references are always 100% correct? Think about what MSDN
had to say about IE7 and the XMLHTTPRequest Object before you answer.
And if that doesn't do it, consider what MSDN has to say about toFixed()
and where it is known *not* to work.

MSDN and W3C are not always correct. Doesn't mean I agree with VK (I
don't care what the default language in IE3.0 was), I do disagree with
the notion (and VK pointed it out) that "Just because something says so
doesn't make it right)". And that alone makes me not care what the specs
say as much as I care what the browsers/UA actually *does* with code.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Mar 4 '06 #19

P: n/a
VK wrote:
VK wrote:
RobG wrote:
In user agents that have a concept of a window object,
it is synonymous with the global object.
I'm aware of only one browser where this is true: Firefox.


You lack of awareness of web browsers is becoming legendary.
Actually it is not true for Firefox neither: they just
tryed to *mimic* that ECMA statement as hard as they could,
so it's really difficult to catch them on the act :-)
And particularly difficult when you don't know what the code you write
is supposed to do, have no analytical skills and don't really comprehend
logic.
Nevertheless the test #2 from my previous post gets them
- I just didn't check it first on Firefox:
LOL
function demo() {
/* Test 2 */
var alert = function(m) {window.alert(m+'bar');}
alert('foo'); // 'foobar'
window.alert('foo'); // 'foo'
// Gocha! :-)
}


So after all this time (what is it, 8-9 years) of supposedly scripting
web browsers you don't actually understand how local variables work? You
create a local variable called - alert - and then assign a reference to
a function object to it and then you don't see why the unqualified
Identifier - alert - is resolved as a reference to that local variable
(and its assigned function) while the property accessor - window.alert -
resolves as a reference to the global - alert - function? How many false
conclusions have you drown over those years form misconceiving the code
that your write?

How can you possibly hope to deduce anything about how web browsers
behave if you don't even know what the code you are writing is supposed
to be doing? Don't you think it would be a good idea to stop bothering
people here with your misconceived nonsense until you have learnt the
basics of the language you are so keen to assert your expertise in?

Richard.
Mar 4 '06 #20

P: n/a
Richard Cornford wrote:
<snip>
... if not resolved as propitious of the object added ... ^^^^^^^^^^ ... caught by being resolved as priorities of .. ^^^^^^^^^^
Should be 'properties' and 'properties' respectively.

<snip>
Respectively if we declare:
window['foo'] = 'bar';
and later call alert(foo) then engine will look first in
the Global scope, fail on it, then look in
the window scope and find it.


With the implication that the global object does not have an
- alert - property or a - foo - property? Neither have been
demonstrated, and the above test shows that both the - window
- object and the global - this - object behave in isolation as
if they have properties corresponding with ECMA 262 defined
global properties, browser global properties, declared local

^^^^^ variables, runtime added properties, etc.

<snip>

Should be "declared global variables".

Richard.
Mar 5 '06 #21

P: n/a
VK

Richard Cornford wrote:
You lack of awareness of web browsers is becoming legendary.


Adding properties to window was an age old and actively used method to
have
any amount of global variables without pre-declaring each and every one

(before new Object() and stuff).
Nevertheless it never was an issue to think that window['foo'] and var
foo
may refer to the same thing ot may override each other.
JavaScript variable and window property was always two completely
separate things.

As Firefox' Global vs. Window behavior went totally against of all my
experience,
I decided to check that I'm not getting senile in my 37.

I installed Netscape Composer 4.5 from my archives, and after a minute
of nostalgie
and the ritual "NN hit" to microsoft.com :-) I run this test:

<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script language="JavaScript1.2">
function test() {
var foo = 1;
window['foo'] = 2;
alert(foo); // displays 1
alert(window['foo']); // displays 2
}
</script>
</head>

<body bgcolor="#FFFFFF" onload="test()">
<p>Test</p>
</body>
</html>

I'm glad to see that my memory is still fine - at least here :-)
And it was exactly the same with Netscape 2.x, Netscape 3.x, IE 3.x,
Netscape 4.x and IE 4.x

Therefore the many times quoted sentence from ECMA specs is just an
extremely bad wording
caused either by bad English or by bad script knowledge or by both. Mr.
Eich must be left then it was written to get some coffee :-)

Therefore the current Firefox scope model is something that never
existed before
Firefox itself and which is not currently implemented anywhere else.
It's the result
of a slavery following of the specification text. In this concern IE is
more "standard"
if we take the "standard" as "something regarded as the most common".

Nevertheless this scope model is already implemented (even if based on
a text errata), so
just another extra difference to deal with. Lucky ECMA did not say that
window properties
are being kept by little green gnomes or something like that. That
would be a real challenge
to implement in the documented way :-)

Mar 5 '06 #22

P: n/a
VK

VK wrote:
I installed Netscape Composer 4.5...


A typo of course, please read instead:

" I installed Netscape Communicator 4.5..."

Mar 5 '06 #23

P: n/a
VK wrote:
Richard Cornford wrote:
You lack of awareness of web browsers is becoming legendary.
Adding properties to window was an age old and actively used
method to have any amount of global variables without
pre-declaring each and every one


And that is relevant because?
(before new Object() and stuff). Nevertheless it never was
an issue to think that window['foo'] and var foo may refer
to the same thing ot may override each other.
If the - var foo; - is declaring a function local variable it is not
expected to refer to the same thing as - window['foo'] -, ever. The
declaring of function local variables and the distinction between local
and global variables is _fundamentally_basic_ to javascript authoring,
and not being able to understand them flags you as an utter incompetent.
All misconceptions that follow from that one basic misconception are
folly built on ignorance.
JavaScript variable and window property was always two
completely separate things.

As Firefox' Global vs. Window behavior went totally against
of all my experience,
Your many years of experience are compliantly worthless. So far you have
not even demonstrated a significant difference in behaviour between IE
and Firefox, let alone anything unexpected in Firefox.
I decided to check that I'm not getting senile in my 37.
It is mental illness that you want to be checking for. You are not
rational.
I installed Netscape Composer 4.5 from my archives, and
after a minute of nostalgie
and the ritual "NN hit" to microsoft.com :-) I run this test:

<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script language="JavaScript1.2">
function test() {
var foo = 1;
window['foo'] = 2;
alert(foo); // displays 1
alert(window['foo']); // displays 2
}
</script>
</head>

<body bgcolor="#FFFFFF" onload="test()">
<p>Test</p>
</body>
</html>

I'm glad to see that my memory is still fine - at least
here :-) And it was exactly the same with Netscape 2.x,
Netscape 3.x, IE 3.x, Netscape 4.x and IE 4.x
Have you fond a single browser where it is not exactly the same?
Therefore
"Therefor"? What is "therefor" about yet another example of a browser
doing precisely what it would be expected to do?
the many times quoted sentence from ECMA specs
is just an extremely bad wording
Which "many times quoted" sentence? If you never state what it is that
you think is being demonstrated how do you expect people to correct your
misconceptions. Don't forget that your 'demonstration' from the
preceding post was not a demonstration of anything but browsers behaving
exactly as they are supposed to.
caused either by bad English or by bad script knowledge
or by both. Mr. Eich must be left then it was written to
get some coffee :-)
Nothing is caused. The problem here is that you don't understand what
you are doing and so you don't understand that what you are observing is
exactly what the code you are writing is supposed to be doing.
Therefore the current Firefox scope model is something that
never existed before Firefox itself and which is not currently
implemented anywhere else.
You have not demonstrated anything divergent or unusual in the handling
of scope in Firefox so there is no evidence for this false assertion.
It's the result of a slavery following of the specification
text. In this concern IE is more "standard" if we take the
"standard" as "something regarded as the most common".
You have not demonstrated any difference in the handling of scope
between Fireforx and IE so this assertion is irrelevant.
Nevertheless this scope model is already implemented (even if
based on a text errata), so just another extra difference to
deal with. Lucky ECMA did not say that window properties are
being kept by little green gnomes or something like that. That
would be a real challenge to implement in the documented way :-)


This whole thing is the product of your maintaining fundamental
misconceptions about the way in which javascript works, even in the face
of numerous corrections and explanations. It is irrational for you to be
so wrong, and demonstrated so wrong so often, and for you not to be able
to see yourself as in error. Worry about mental illness not senility.

Richard.
Mar 5 '06 #24

P: n/a
VK

Richard Cornford wrote:
Your many years of experience are compliantly worthless. So far you have
not even demonstrated a significant difference in behaviour between IE
and Firefox, let alone anything unexpected in Firefox.


It is difficult to argue with a real believer. It is double difficult
to argue with an agressive believer, who's ready to "kill for his
faith" :-)

I dared to check you posting history and I see them back to the year
2000, which means that you were reading Books of ECMA six years in the
row by now. That makes damage for sure. :-)
My ignorance about Books of ECMA sometimes is a default but sometimes
it is a great benefit as I kept the ability to accept new facts or to
give new explanation to old ones.
IMHO this ability has been seriously weakened from your side as for too
many years your preoccupation was to prove that whatever happens in the
Web was described or predicted in the Books of ECMA. Sorry if I sound
nasty, but seems close to the truth.

Believe you me or not but at the moment of my first post in this thread
(about Global vs. Window scope in IE and Opera) I had no idea about the
following article on MSDN. I found it only tonight while trying to save
the rest of my sanity - as it happens with me after some discussions
with selected people in this newsgroup :-)

<blockquote
cite="http://msdn.microsoft.com/workshop/author/perf/perftips.asp">
"Scope Your Object References Wisely"

Within a script, every reference to an object amounts to two calls
from the scripting engine to the DHTML Object Model. For those
unfamiliar with or interested in the intimate details of Automation,
refer to the documentation on IDispatch::GetIDsOfNames and
IDispatch::Invoke
in the Microsoft Platform software development kit (SDK).
....
When Internet Explorer parses a page it accounts for all the objects
on the page for which ID attributes have been explicitly specified.
It adds them to the global namespace of the scripting engine,
allowing you to refer to them directly. That means that the following
is excessive.
<SCRIPT>
var sText = document.all.div1.innerText;
</SCRIPT>
In addition to the extra bytes that are passed across the network
and parsed by the scripting engine, four extra calls are made by
the script engine back to Internet Explorer in order to retrieve
the innerText property of the div.

Notable exceptions to this minimalist approach include the following:
Accessing elements contained within a form.
Accessing properties of an iframe.
Accessing properties of the window object.

When a scripting engine encounters a scoped object model reference in
your code,
the engine needs to resolve the reference by looking up the left-most
piece of that
reference in a look-up table. Two factors influence the scripting
engine's ability
to perform the look-up:

The number of entries in the look-up table.
The scope of the reference.
The number of entries in the table corresponds to the number of global
variables,
named objects, and functions that you have defined on your page.
Thus, you should only declare the ID attribute on those elements
that you explicitly wish to manipulate through script.

As mentioned above, there's a right way and a wrong way to scope
references. When you've assigned an ID attribute to an element, there's
no reason to access the corresponding object through document.all.
Armed with this information, you might think that you should minimize
your object model references in all cases. Let's look at another common
example where this rule doesn't apply:

var sUA = navigator.userAgent;
The code works. It stores the HTTP_USER_AGENT string in the variable
sUA. In order for the scripting engine to resolve this reference,
however, it first attempts to find an object named navigator in the
global look-up table. After looking through the entire table and not
finding such a named item, the engine has to walk through the table
again asking each of the global objects if it supports the navigator
object. When it finally encounters the global window object, the object
that exposes the navigator property, it can then retrieve the userAgent
property. A better way to handle this situation, especially on a page
containing many globally named items, is to fully scope the reference
as follows:

var sUA = window.navigator.userAgent;
If all this talk about look-up tables and global objects has your head
spinning, just remember this simple rule: fully scope your references
to members of the window object. A list of these members is provided in
the DHTML Reference.
</blockquote>

And as a nice parting comment :-)

<q
cite="<http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=102277&SiteID=1">
...unlike in Firefox, in IE the window object isn't exactly the
JScript global object.
This was originally so that multiple script languages could safely
coexist in a web page.
</q>

.... sweet dreems ;-)

Mar 5 '06 #25

P: n/a
VK wrote:
Richard Cornford wrote:
Your many years of experience are compliantly worthless. So far you have
not even demonstrated a significant difference in behaviour between IE
and Firefox, let alone anything unexpected in Firefox.


It is difficult to argue with a real believer. It is double difficult
to argue with an agressive believer, who's ready to "kill for his
faith" :-)


Your problem is that /you/ are making this a question of faith. It is not.
It is a matter of fact. It is based on hard evidence that you are presented
over and over again. Still you choose to ignore it, and to listen to the
voices in your head instead which originate from your misunderstanding of
informal texts combined with your unjustified snotty attitude. The
described behavior has been specified, and it was implemented as specified.
Even before the specification was actually issued.
PointedEars
Mar 5 '06 #26

P: n/a
VK wrote:
Richard Cornford wrote:
Your many years of experience are compliantly worthless.
So far you have not even demonstrated a significant
difference in behaviour between IE and Firefox, let alone
anything unexpected in Firefox.
It is difficult to argue with a real believer. It is double
difficult to argue with an agressive believer, who's ready
to "kill for his faith" :-)


If you posted code that showed any browser exhibiting behaviour that
differs from the behaviour that would be expected of a 100% ECMA 262
conforming javascript implementation then there would be no question of
belief, we would be in the realm of facts. But so far in this thread you
have only managed to post code that demonstrates browsers behaving in a
way that look significant in your understanding of the language, but
actually have no baring on the assertions that you are making to explain
them.
I dared to check you posting history and I see them back
to the year 2000,
You cannot even competently perform an archive search.
which means that you were reading Books of ECMA six years
in the row by now.
As your first 'fact' is wrong that conclusion is inevitably also wrong.
But your conclusion would be wrong even if you had got the date right.
It took me a while to see the advantages in gaining a technical
understanding of the language specification so the period over which I
have been reading, and referring to, ECMA 262 is shorter than the period
over which I have been posting to this group.
That makes damage for sure. :-)
Yes, I can look at written source code and know precisely how it will
behave before it is executed, while you don't even understand what the
code you write is doing after it is executed; that is real 'damage'
isn't it?
My ignorance about Books of ECMA sometimes is a default but
sometimes it is a great benefit as I kept the ability to
accept new facts or to give new explanation to old ones.
By which you mean that having no technical understanding of javascript
allows you freedom to fabricate explanations and terminology off the top
of your head.
IMHO this ability has been seriously weakened from your side
as for too many years your preoccupation was to prove that
whatever happens in the Web was described or predicted in
the Books of ECMA. Sorry if I sound nasty, but seems close
to the truth.
There is no preoccupation to 'prove' that anything "was described or
predicted in the Books of ECMA". We are not talking about the works of
Nostradamus, ECMA 262 is a technical specification for a programming
language. It prescribes how the core language will behave, from the
interpretation of source code to the evaluation of simplest expression,
in near total precision. It is also the standard that every current web
browser javascript implementation states that it implements, as was the
intention when it was created. It provides sufficient detail to allow
code to be written with a certain expectation of how it will be
interpreted and behave, and it provides a consistent set of well-defined
terminology for use in technical discussions of the subject.

It is also the only source that will answer particular technical
questions, such as which side of an equality expression will be
evaluated first. You won't find that detail in references, user guides
and (most) informal texts, but those are not technical documents and
while language implementers can assert that they implement ECMA 262 they
don't need to put that detail in their non-technical documents as you
can always go to the standard to get the real details.

But in any event, the ability to accept "new facts" is irrelevant while
no new facts are presented, and the ability to identify and reject bogus
facts is more valuable in the growth of knowledge than the ability to
accept new facts.
Believe you me or not but at the moment of my first post
in this thread (about Global vs. Window scope in IE and
Opera) I had no idea about the following article on MSDN.
No, I do believe that you made it up off the top of your head based on
misinterpretations of various sources and code that you did not
understand yourself.
I found it only tonight while
trying to save the rest of my sanity - as it happens with me after
some discussions with selected people in this newsgroup :-)

<blockquote
cite="http://msdn.microsoft.com/workshop/author/perf/perftips.asp">
"Scope Your Object References Wisely"

Within a script, every reference to an object amounts to two
calls from the scripting engine to the DHTML Object Model.
For those unfamiliar with or interested in the intimate details
of Automation, refer to the documentation on
IDispatch::GetIDsOfNames and IDispatch::Invoke
in the Microsoft Platform software development kit (SDK).
...
When Internet Explorer parses a page it accounts for all
the objects on the page for which ID attributes have been
explicitly specified. It adds them to the global namespace
of the scripting engine, allowing you to refer to them
directly. That means that the following is excessive.
<SCRIPT>
var sText = document.all.div1.innerText;
</SCRIPT>
In addition to the extra bytes that are passed across
the network and parsed by the scripting engine, four
extra calls are made by the script engine back to
Internet Explorer in order to retrieve the innerText
property of the div.

Notable exceptions to this minimalist approach include
the following:
Accessing elements contained within a form.
Accessing properties of an iframe.
Accessing properties of the window object.

When a scripting engine encounters a scoped object model
reference in your code, the engine needs to resolve the
reference by looking up the left-most piece of that
reference in a look-up table. Two factors influence
the scripting engine's ability to perform the look-up:

The number of entries in the look-up table.
The scope of the reference.
The number of entries in the table corresponds to the
number of global variables,
named objects, and functions that you have defined on
your page. Thus, you should only declare the ID
attribute on those elements that you explicitly wish
to manipulate through script.

As mentioned above, there's a right way and a wrong
way to scope references. When you've assigned an ID
attribute to an element, there's no reason to access
the corresponding object through document.all. Armed
with this information, you might think that you should
minimize your object model references in all cases.
Let's look at another common example where this rule
doesn't apply:

var sUA = navigator.userAgent;
The code works. It stores the HTTP_USER_AGENT string
in the variable sUA. In order for the scripting engine
to resolve this reference, however, it first attempts
to find an object named navigator in the global look-up
table. After looking through the entire table and not
finding such a named item, the engine has to walk through
the table again asking each of the global objects if it
supports the navigator object. When it finally encounters
the global window object, the object that exposes the
navigator property, it can then retrieve the userAgent
property. A better way to handle this situation, especially
on a page containing many globally named items, is to fully
scope the reference as follows:

var sUA = window.navigator.userAgent;
If all this talk about look-up tables and global objects
has your head spinning, just remember this simple rule:
fully scope your references to members of the window object.
A list of these members is provided in the DHTML Reference.
</blockquote>
Well, that does not say that there is an object below the ECMAScript
global object on the scope chain. It is an informal text describing (or
appearing to describe) the internal details of the resolution of the
properties of the global object. And as these details are internal they
have no consequences for the author of javascript code as they do not
change the ability of IE to behave in accordance with ECMA 262.

That is, this document is irrelevant except that it suggests that
features of the internal mechanism would result in particular styles of
property accessor being resolved faster than others. On the other hand,
if true, those might be exploitable details, particularly for those
working on an IE only Intranet. The concrete claim of that article is
that:-

var sUA = navigator.userAgent;

- will take longer to resolve than:-

var sUA = window.navigator.userAgent;

- "especially on a page containing many globally named items".

That is a very specific claim, and relatively easy to verify, or refute.
You may prefer to perceive my actions as driven entirely by a
theoretical approach but I am actually very keen on experimentation and
demonstration. Here is a test script to verify the above claim, it
document.writes 2000 IDed DIV elements as that should qualify as "on a
page containing many globally named items" and so show the advantages of
qualifying the property accessor with - window - to its maximum extent:-

<html>
<head>
<title>navigator tests</title>
<script type="text/javascript">

var frm = null;
var fncts = [
/* Timing of an empty loop to estimate the overheads of the
test itself. */
function(p){
var lim = +frm['loopLimit'].value;
var N, totTime, stTime = new Date().getTime();
for(var c = 0;c < lim;c++){
N = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows __)';
}
totTime = (new Date().getTime() - stTime);
frm["Dur"+p].value = totTime;
frm["Avr"+p].value = (totTime/lim);
frm["Res"+p].value = N;
act(p+1);
},
function(p){
var lim = +frm['loopLimit'].value;
var N, totTime, stTime = new Date().getTime();
for(var c = 0;c < lim;c++){
N = window.navigator.userAgent;
}
totTime = (new Date().getTime() - stTime);
frm["Dur"+p].value = totTime;
frm["Avr"+p].value = (totTime/lim);
frm["Res"+p].value = N;
act(p+1);
},
function(p){
var lim = +frm['loopLimit'].value;
var N, totTime, stTime;
stTime = new Date().getTime();
for(var c = 0;c < lim;c++){
N = navigator.userAgent;
}
totTime = (new Date().getTime() - stTime);
frm["Dur"+p].value = totTime;
frm["Avr"+p].value = (totTime/lim);
frm["Res"+p].value = N;
act(p+1);
}
];

var f;
var running = false;
function setButtons(bl){
frm['loopLimit'].disabled = bl;
var sw = frm['bt'];
if(typeof sw.length == 'undefined'){
sw = [sw];
}
for(var c = 0;c < sw.length;c++){
sw[c].disabled = bl;
}
}
function doTests(){
if(!running){
frm = document.forms['f'].elements;
setButtons(true);
frm["Dur0"].value = '';frm["Avr0"].value = '';
for(var c = 1;c < fncts.length;c++){
frm["Dur"+c].value = '';
frm["Avr"+c].value = '';
frm["CAvr"+c].value = '';
frm["PAvr"+c].value = '';
frm["Res"+c].value = '';
}
running = true;
act(0);
}
}
function act(p){
/* setTimeout is used to minimise the occurrences
of 'a script on this page is running slow' dialogs. */
if(p >= fncts.length){
setTimeout('report()',100);
}else{
setTimeout(('(f = fncts['+p+'])('+p+');'),200);
}
}
function report(){
var c, evaC, lim = +frm['loopLimit'].value;
var emDur = +frm["Dur0"].value
var unaC = (frm["Dur"+(fncts.length-1)].value - emDur) / lim;
frm["CAvr"+(fncts.length-1)].value = unaC;
frm["PAvr"+(fncts.length-1)].value = '100';
for(c = 1;c < (fncts.length-1);c++){
evaC = (frm["Dur"+c].value - emDur) / lim;
frm["CAvr"+c].value = evaC;
frm["PAvr"+c].value = ((evaC/unaC)*100);
}
setButtons(false);
running = false;
}

</script>
</head>
<body>
<div>
<form name="f" action="#">
Loop Length = <input type="text" value="1300000"
name="loopLimit"><br><br>
<input type="button" value="Test" name="bt" onclick="doTests();">
Repeat tests to reduce/expose the influence of background tasks.
<br><br>
Empty Loop Duration (milliseconds) = <input type="text" value="X"
name="Dur0"><br>
Empty Loop Average (milliseconds) = <input type="text" value="X"
name="Avr0" size="22"><br>
(result = <input type="text" value="X" name="Res0" size="22">)<br><br>
<br>

<br>
<code>window.navigator.userAgent</code> Duration (milliseconds) =
<input type="text" value="X" name="Dur1"><br>
<code>window.navigator.userAgent</code> Average (milliseconds) =
<input type="text" value="X" name="Avr1" size="22"><br>
(result = <input type="text" value="X" name="Res1" size="22">)<br><br>
<br>
<code>navigator.userAgent</code> Duration (milliseconds) =
<input type="text" value="X" name="Dur2"><br>
<code>navigator.userAgent</code> Average (milliseconds) =
<input type="text" value="X" name="Avr2" size="22"><br>
(result = <input type="text" value="X"
name="Res2" size="22">)<br><br>
<input type="button" value="Test" name="bt" onclick="doTests();">
Repeat tests to reduce/expose the influence of background tasks.
<br><br>

Results: (duration of test - duration of empty loop) / loop length<br>

<code>window.navigator.userAgent</code> Average (milliseconds) =
<input type="text" value="X" name="CAvr1" size="22"><br>

<code>navigator.userAgent</code> Average (milliseconds) =
<input type="text" value="X" name="CAvr2" size="22"><br>
<br>
<table><tbody><tr><th></th>
<th>Differences (<code>navigator.userAgent</code> = 100%)</th></tr>

<tr><td><code>window.navigator.userAgent</code></td><td>
<input type="text" value="X" name="PAvr1"size="22">%</td></tr>

<tr><td><code>navigator.userAgent</code></td><td>
<input type="text" value="X" name="PAvr2"size="22">%</td></tr>

</tbody></table>

</form>
</div>
<script type="text/javascript">
for(var c = 0;c < 2000;++c){
document.write('<div id=\"test'+c+'\">test'+c+' div<\/div>');
}
</script>

</body>
</html>

And using that test script these are the results I got on the various
stated IE versions and OS/processor combinations:-

IE 5.50.4807.2300IC
Windows NT4 - AMD K6-2 500MHz
| Per-lookup | Difference
--------------------------------------------------------
window.navigator.userAgent | 0.10229 ms | 140.237%
navigator.userAgent | 0.07294 ms | 100%
--------------------------------------------------------
IE 5.50.4134.0100
Windows ME - Celeron 700MHz
| Per-lookup | Difference
--------------------------------------------------------
window.navigator.userAgent | 0.07744 ms | 171.441%
navigator.userAgent | 0.04517 ms | 100%
--------------------------------------------------------
IE 6.0.2800.1106
Windows 98 - P3 500MHz
| Per-lookup | Difference
--------------------------------------------------------
window.navigator.userAgent | 0.09646 ms | 128.973%
navigator.userAgent | 0.07479 ms | 100%
--------------------------------------------------------
IE 6.0.3790.1830
Windows XP Pro 64bit - AMD Athlon 64X2 4400+ (2*2200MHz)
| Per-lookup | Difference
--------------------------------------------------------
window.navigator.userAgent | 0.00867 ms | 137.596%
navigator.userAgent | 0.00630 ms | 100%
--------------------------------------------------------
IE 6.0.2900.2180.xpsp-sp2-rtm.040803.2158
Windows XP Pro 32bit - AMD Athlon 64X2 4400+ (2*2200MHz)
| Per-lookup | Difference
--------------------------------------------------------
window.navigator.userAgent | 0.01064 ms | 129.220%
navigator.userAgent | 0.00823 ms | 100%
--------------------------------------------------------

Oh, look, - navigator.userAgent - resolves quicker than -
window.navigator.userAgent - in every test, by 29 - 79%. That is in
complete *contradiction* to the stated 'fact' in the article cited
above. How can this be, MSDN publishing material that makes statements
that are the opposite of the verifiable truth?

A charitable interpretation may be that this article refers to a
language implementation that has disappeared into the mists of history.
A less charitable interpretation would be that the author did not know
what he was talking about, or did not understand it well enough to draw
accurate conclusions. Either way an article that had little practical
relevance to browser scripting is shown by empirical testing to be false
in its concrete claims and so lacks credibility in general.
And as a nice parting comment :-)

<q
cite="<http://forums.microsoft.com/MSDN/Sho...ID=102277&Site
ID=1">
<snip>

Oh, very good, cite a random contribution to a Microsoft hosted public
newsgroup. That is about as authoritative as someone citing one of your
Usenet posts as an authority on javascript. And a post by an individual
who states:- "There is no way to get at the script global object to
enumerate its members", which demonstrates how much he knows:-

<URL: http://www.litotes.demon.co.uk/ie50/...50&prop=window >
... sweet dreems ;-)


Dream on.

Richard.
Mar 6 '06 #27

This discussion thread is closed

Replies have been disabled for this discussion.