Sunday, May 30, 2010

passing variables between scripts on the same page

QUERY:

Hi,
I have a page with several javascripts in it. For some reason I can't
seem to pass variables between the scripts and I need to for one of
the functions.

I understand this can be done by giving each script a name and
referencing the script name with the variable.
Could you provide an example of this,
or another method of passing variables between scripts.


Solution: by declaring the variables globally



I believe I see your problem: like some other languages, JavaScript
has a notion of 'scope' (although quite a quite limited one in
comparison). If you declare a variable inside of one function is JS,
you can't use it in another function. The simple work around is to
declare all variables 'globally' (often considered bad style in other
languages, but pretty common in JS). Alternatively, you could make the
two helper functions return values and call them from calc, but the
other way is probably more straight forward for you. Make the
following simple change and your script should work:

<SCRIPT Type="text/javascript" Language="JavaScript">
<!--
var variable1; // declare the variables outside of the functions
var variable2;

function calc(){
var x = (variable1 / variable2);
}
function userInput1(){
variable1 = adb;
}
function userInput2(){
variable2 = arnd;
}
//-->
</SCRIPT>

No comments:

Post a Comment