...

View Full Version : Keeping variables between functions



blitz104
12-13-2009, 04:42 AM
I've noticed that if you declare a variable in one function, then call another function, the variables cannot be accessed in that function. Is there any way to get the value of a variable declared in a different function?

A1ien51
12-13-2009, 05:04 AM
Well if you declare them in the function they are local.

Make them global? Learn about OOP?

Eric

rnd me
12-13-2009, 06:07 AM
I've noticed that if you declare a variable in one function, then call another function, the variables cannot be accessed in that function. Is there any way to get the value of a variable declared in a different function?

no. as you describe and assuming un-nested functions, absolutely not.
not unless you make them available in some other fashion.

Philip M
12-13-2009, 08:49 AM
Local variables exist only inside a particular function, hence they said to have Local Scope. Global variables on the other hand are present throughout the script and their values can be accessed by any function. Thus, they are said to have Global Scope.

A variable is global if
a) it is declared with or without the var keyword outside a function
b) it is declared without the var keyword within a function.

A variable is local if it is declared with the var keyword within a function.

It is possible to have two variables in a script with the same name, one global and one local.
Obviously this is very undesirable and not recommended.


<script type = "text/javascript">
var x = 10;
alert (x); // x is global
y = 5; // y is also global
function show() {
var y = 20; // this y is local
alert (y);
}

show()
</script>

Trinithis
12-14-2009, 07:29 AM
If you don't yet know OOP, my advise is to namespace the functions and store the needed variables in the namespace:



var Foo = {};

Foo.x = 1;

Foo.abra = function () {
Foo.x = Foo.x * 2;
return 1;
};

Foo.kadabra = function () {
return Foo.x;
};

alert (Foo.abra);
alert (Foo.kadabra);
alert (Foo.abra);
alert (Foo.kadabra);
alert (Foo.abra);
alert (Foo.kadabra);

rnd me
12-14-2009, 12:04 PM
If you don't yet know OOP, my advise is to namespace the functions and store the needed variables in the namespace:


at the slight cost of speed, you can code this more succinctly using with:




//pre define all vars here:
var Foo = {x:1};

//your functions inside a with can share named properties like they are vars.
with(Foo){
Foo.abra = function () {
x = x * 2;
return 1;
};

Foo.kadabra = function () {
return x;
};

alert (abra());
alert (kadabra());
alert (abra());
alert (kadabra());
alert (abra());
alert (kadabra());
}//end with


note that these fake vars can be set, but not created by name.
if a property doesn't exist and you just use the name, you will create a global.
you can manually create new "vars" by adding them onto the namespace from anywhere (Foo in this case).



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum