Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call variables from one javascript file to another

How can I call the variables that I stored in one javascript file from another?

var.js

var VAR = new Object;
VAR.myvalue = "Yeah!";

then I want to use VAR.myvalue here

sample.js

alert(VAR.myvalue);
like image 758
Robin Carlo Catacutan Avatar asked Dec 02 '11 03:12

Robin Carlo Catacutan


People also ask

How is a variable accessed from another file?

The variable number is declared globally and may be accessed from other file when including its declaration with the “ extern ” prefix. However, the variable coefficient is only accessible from the file in which it is declared and only from that point on (it is not visible in function main .

How do I link two JavaScript files?

We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require, jQuery's getScript function, and Fetch Loading.

How do you import a variable in JavaScript?

To import a variable from another file in JavaScript:Export the variable from file A , e.g. export const str = 'Hello world' . Import the variable in file B as import { str } from './another-file. js' .

How do I move an object from one JavaScript file to another?

Answer: Use the export and import Statement Since ECMAScript 6 (or ES6) you can use the export or import statement in a JavaScript file to export or import variables, functions, classes or any other entity to/from other JS files.


2 Answers

First, instead of

var VAR = new Object;
VAR.myvalue = "Yeah!";

Opt for

var VAR = {
    myvalue: "Yeah!"
 };

But so long as var.js is referenced first, before sample.js, what you have should work fine.

var.js will declare, and initialize VAR, which will be read from the script declared in sample.js

like image 187
Adam Rackis Avatar answered Oct 09 '22 16:10

Adam Rackis


Include both JavaScript file in one HTML file, place sample.js after var.js so that VAR.myvalue is valid:

<script type="text/javascript" src="var.js"></script>
<script type="text/javascript" src="sample.js"></script>
like image 37
ExpExc Avatar answered Oct 09 '22 17:10

ExpExc