Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Declaring global variables 2

Status
Not open for further replies.

Sleidia

Technical User
May 4, 2001
1,284
FR

Hi guys :)

Is it possible to declare a variable global from inside a function?

How do you make sure a global variable will never be polluted (ie:duplicate name) by a foreign script also using global variables?

Thanks!
 
You can declare a global variable from within a function by using the window array:
Code:
function foo() {
  window['bar'] = 'wibble';
}
The variable is now able to be referenced as either "wibble" or "window['wibble']".

Cheers,
Jeff

[tt]Jeff's Blog [!]@[/!] CodeRambler
[/tt]

Make sure your web page and css validates properly against the doctype you have chosen - before you attempt to debug a problem!

FAQ216-6094
 

Thanks :)

So, to answer the second question, woudn't it be wise to have something like this? :

Code:
function my_function() {

window['my_function']['my_var'] = 'my value';

}
 
You can also declare a global variable inside a function simply by omitting the "var" keyword:

Code:
function wibble() {
   abc = 1; // this will be global
   var def = 2; // this will be local
}

You can't stop a foreign script from overwriting your own global variables, but you can test whether a foreign script is using a variable or not:

Code:
if (typeof(window['globalVariableName']) == 'undefined') {
   // it's same to use 'globalVariableName' now...
}

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top