467,161 Members | 868 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,161 developers. It's quick & easy.

create global variable from inside the function?

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
Oct 24 '06 #1
  • viewed: 11382
Share:
3 Replies

Ralph wrote:
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

Oct 24 '06 #2
ASM
Ralph a écrit :
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
One thing I can do is create the global array
do you mean array of globals ?
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
Oct 24 '06 #3
ASM wrote:
Ralph a écrit :
>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
>One thing I can do is create the global array

do you mean array of globals ?
>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
Oct 25 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Japhy | last post: by
4 posts views Thread by Andrew V. Romero | last post: by
reply views Thread by Bryan Parkoff | last post: by
8 posts views Thread by chellappa | last post: by
9 posts views Thread by ruca | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.