0

If I wanted to extract a variable from an external js file to another external js file.. How would I do that?

For example, if I had a file call example1.js that contained the following code

 var test = 1;

How would I obtain the value of variable test and put it into my example2.js?

Thanks for the help!

Roy
  • 43,878
  • 2
  • 26
  • 26

4 Answers4

1

You have declare that variable globally. And make sure you have loaded both the files in order.

example1.js

var test = 1;
function myFunction()
{
}

example2.js

alert(test);

Assuming you are using this files in php, You have to load the files in order:

<script src="example1.js"></script>
<script src="example2.js"></script>
Bhushan
  • 6,151
  • 13
  • 58
  • 91
1

In case, not interested in global-variable use like this,

exapmle1.js

var example1 =
{
    test1 : 1,
    someFunctionName : function(){.....}
}

exapmle2.js

var example2 =
{
    someFunctionName : function(){ alert(example1.test1) }
}
Veeramani3189
  • 23
  • 1
  • 7
0

You could try removing "var" so make it global to all your js files (no matter if its withing a function), still you will have to load the js files in order to avoid problems.

Also you could try add a property to window as shows the answer here:

Define global variable in a JavaScript function

But be carefully of doing this.

Community
  • 1
  • 1
Allende
  • 1,480
  • 2
  • 22
  • 39
0

Since you tagged this question with php ,

I am assuming you need to copy code from example1.js to example2.js , Try this below code

file_put_contents("example2.js",file_get_contents("example1.js"));
Vishnu
  • 2,372
  • 6
  • 36
  • 58