Connecting Tech Pros Worldwide Forums | Help | Site Map

create global variable from inside the function?

Ralph
Guest
 
Posts: n/a
#1: Oct 24 '06
Hi

Is this possible?

One thing I can do is create the global array and add the new item to it
from inside the function but that's not what I'm looking for.

Thank you

Ralph



RobG
Guest
 
Posts: n/a
#2: Oct 25 '06

re: create global variable from inside the function?



Ralph wrote:
Quote:
Hi
>
Is this possible?
>
One thing I can do is create the global array and add the new item to it
from inside the function but that's not what I'm looking for.
function (){
window.anArray = ['foo', 'bar', 1, 2, 3];
}

Maybe you'd prefer:

var _global = this;
function (){
_global.anArray = ['foo', 'bar', 1, 2, 3];
}


It is a good idea to avoid global variables where possible, make them
properties of some other object - a kind of namespace to keep your
stuff from colliding with other stuff.


--
Rob

ASM
Guest
 
Posts: n/a
#3: Oct 25 '06

re: create global variable from inside the function?


Ralph a écrit :
Quote:
Hi
>
Is this possible?
var c = 'bonjour';

function glob() {
var a = 'hello';
b = 'saluti';
}

glob();

alert(a); // undefined
alert(b); // saluti
alert(c); // bonjour

all variables in JS are global
except those declared in a function and prefixed with var
Quote:
One thing I can do is create the global array
do you mean array of globals ?
Quote:
and add the new item to it
from inside the function but that's not what I'm looking for.
function arr() {
tablo = new Array('one','two');
}
function arrAdd() {
if( typeof (tablo) == 'undefined') arr();
for(var i=0; i<arguments.length; i++)
tablo[tablo.length] = arguments[i];
}

arrAdd('three','for','five');

alert(tablo[4]); // five

--
ASM
Ralph
Guest
 
Posts: n/a
#4: Oct 25 '06

re: create global variable from inside the function?


ASM wrote:
Quote:
Ralph a écrit :
Quote:
>Hi
>>
>Is this possible?
>
var c = 'bonjour';
>
function glob() {
var a = 'hello';
b = 'saluti';
}
>
glob();
>
alert(a); // undefined
alert(b); // saluti
alert(c); // bonjour
>
all variables in JS are global
except those declared in a function and prefixed with var
>
Quote:
>One thing I can do is create the global array
>
do you mean array of globals ?
>
Quote:
>and add the new item to it from inside the function but that's not
>what I'm looking for.
>
function arr() {
tablo = new Array('one','two');
}
function arrAdd() {
if( typeof (tablo) == 'undefined') arr();
for(var i=0; i<arguments.length; i++)
tablo[tablo.length] = arguments[i];
}
>
arrAdd('three','for','five');
>
alert(tablo[4]); // five
>
Thank you all. That what I was looking for.
Ralph
Closed Thread


Similar JavaScript / Ajax / DHTML bytes