declare globals in .JS file

B

Bill

If I declared an array or object in a .JS file, should it not be global
throughout all the files which reference it?
 
L

Lee

Bill said:
If I declared an array or object in a .JS file, should it not be global
throughout all the files which reference it?

No.
The .js file is just a text file. It doesn't provide any place to
store the data.
As each file loads and interprets the file, each one creates its
own storage space.
 
F

Fred Serry

Bill said:
If I declared an array or object in a .JS file, should it not be global
throughout all the files which reference it?

Hi Bill.

Short answer: No.

Long version: A .js file is no more and no less than an include.

<script type=text/javascript src=a.js><script>
(a.js being: var a=1)

--and--

<script type=text/javascript>var a=1<script>

are identical.

If you want a global var or object between pages, use cookies, frames or a
db serverside.

Fred
 
C

Chris Riesbeck

Lee said:
Bill said:

No.
The .js file is just a text file. It doesn't provide any place to
store the data.
As each file loads and interprets the file, each one creates its
own storage space.

I think it's better to think in terms of windows, not files.
Variables are attached to window objects. Loading a window
or frame creates a new window object. The old window
object is gone, along with its variables. In one window,
you can load several .js files and they can refer to one
common set of variables.

Hence a common technique for "global" variables is to use
frames and define the variables in the frameset or frame
that never goes away. Any frame can access the frameset
variables using top.variablename.
 
L

Lee

Chris Riesbeck said:
I think it's better to think in terms of windows, not files.

Yes. That was actually a blunder on my part.
I had meant to say "As each *window* loads ...".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top