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!

1
  • why did you tag this with php? Commented Feb 13, 2014 at 6:43

4 Answers 4

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>
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.