northranger79510
northranger79510

Reputation: 1

Obtaining Variable from External Javascript File

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!

Upvotes: 0

Views: 63

Answers (4)

Veeramani3189
Veeramani3189

Reputation: 23

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) }
}

Upvotes: 1

Vishnu
Vishnu

Reputation: 2452

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"));

Upvotes: 0

Bhushan
Bhushan

Reputation: 6181

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>

Upvotes: 1

Allende
Allende

Reputation: 1482

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.

Upvotes: 0

Related Questions