Home > Article > Web Front-end > How Can I Access Variables Defined in One JavaScript File from Another?
Accessing Variables Across Files in JavaScript
Can you access variables from different JavaScript files? Yes, it's possible to use a variable defined in a file like first.js within another file like second.js.
Global Scope and Access
In JavaScript, if a variable is declared in the global scope (i.e., not within a function), it becomes available to all scripts loaded after it has been defined. This means that a variable named colorCodes in first.js can be accessed in second.js.
Example Code
Here's an example:
<code class="javascript">// first.js var colorCodes = { back : "#fff", front : "#888", side : "#369" };</code>
<code class="javascript">// second.js alert(colorCodes.back); // alerts "#fff"</code>
Load Order and Script Tags
In the HTML file, ensure that first.js is loaded before second.js for the variable to be available in the second script:
<code class="html"><script type="text/javascript" src="first.js"></script> <script type="text/javascript" src="second.js"></script></code>
Alternative Approach
You can also store the variable on the window object (or this in the global scope) to access it:
<code class="javascript">// first.js window.colorCodes = { // ... same object as before };</code>
<code class="javascript">// second.js alert(window.colorCodes.back); // alerts "#fff"</code>
The above is the detailed content of How Can I Access Variables Defined in One JavaScript File from Another?. For more information, please follow other related articles on the PHP Chinese website!