how to declare a variable which i can use in another function.
function1()
{
var x;
}
i need to use "x" variable in another function asy function2
function2()
{
alert (x);
}
| SitePoint Sponsor |

how to declare a variable which i can use in another function.
function1()
{
var x;
}
i need to use "x" variable in another function asy function2
function2()
{
alert (x);
}
Happy Coding!!!
Bruce Lee.

Declare it outside the function.





Hi,
It will also become global if you omit the var keyword.
ERIK RIKLUND :: Yes, I've been gone quite a while.





In addition, you can use the window object's array notation: window["var_name"]. Summing up:
1)Declared outside any function:2)Inside the function without the var keyword:Code:var x = "hello"; function f1() { alert(x); } function f2() { alert (x); } f1(); f2();3)Using the window object:Code:function f1() { x= "hello" alert(x); } function f2() { alert (x); } f1(); f2();In my opinion, 1 and 3 are preferable.Code:function f1() { window["x"] = "hello" alert(x); } function f2() { alert (x); } f1(); f2();





For the sake of completeness, you can also use "static member" notation.
"window" is not that good because less portable.Code:function a () { a.x = 10; } function b() { alert(a.x) } a() b()
Bookmarks