[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1148
  • Last Modified:

How to declare a javascript variable as global

I want to declare few javascript variales as global in one js file and would like to use them in another js file's function
0
dharemshpatel
Asked:
dharemshpatel
2 Solutions
 
ALNMOOCommented:
Any variable inside a function with var keyword will be a local variable & if it is without var, it will have a global variable
0
 
dharemshpatelAuthor Commented:
I have tried the same,

I have defined strVal= 'test' in one js file
and tried to alert the same in another js file (note: i have included the first js file in second). Still it doesn't work.
0
 
ALNMOOCommented:
If you can post your JS test code it will be better. or try this code, it should work.



function myfunction1()
{
txt = 'Global Var';
 
}
 
 
function myfunction()
{
alert(txt);
 
}

Open in new window

0
 
hieloCommented:
Any variable declared outside a function is global. From within functions, you have access to these variables if:
1. you do not declare a variable with the same name prefixed with "var"
2. none of the functions parameters is named the same as the "global" variable in question

>>note: i have included the first js file in second
How are you doing the including?  Order matters. Here are a couple of examples:

//file1.js
var msg = "Hello World";

//file2.js
function report()
{
  alert( msg );
}
report();

//test_a.html: This will work
<html>
<head>
 <script src="file1.js" type="text/javascript"></script>
 <script src="file2.js" type="text/javascript"></script>
</head>
<body></body>
</html>

//test_b.html: This will NOT work. Why? When file2.js is included, msg does not exist yet!
<html>
<head>
 <script src="file2.js" type="text/javascript"></script>
 <script src="file1.js" type="text/javascript"></script>
</head>
<body></body>
</html>
0
 
Computer101Commented:
Forced accept.

Computer101
EE Admin
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now