0

I have two javascript files included at the header of my website. Both files contains almost same variables.

If I have header like this

 <head>
 <script src="http://127.0.0.1/js/file1.js" type="text/javascript"></script>
 <script src="http://127.0.0.1/js/file2.js" type="text/javascript"></script>
 </head>

Is it possible to access vars defined in file1.js from file2.js ?

This is what i`m trying

 file1
 $(function() {
 var x = 1;
 });
file2
 $(function() {
 console.log(x); //This dosen`t work. Can`t access var
 });
asked Oct 5, 2010 at 14:08
2
  • Is it possible to access vars defined in file1.js from file2.js ? defined how? Can you make an example? Commented Oct 5, 2010 at 14:10
  • Duplicate: stackoverflow.com/questions/751882/… Commented Oct 5, 2010 at 14:11

5 Answers 5

2

It's not possible the way you're doing it. Variables have to exist in the global scope to be available across files. In your example, x is defined in the scope of the anonymous function. If you changed it to

// file1 
var x;
$(function() { 
 x = 1; 
}); 

then you could access x from your second file.

answered Oct 5, 2010 at 14:27
Sign up to request clarification or add additional context in comments.

Comments

0

Yep, that should work. As long as the variable is a global variable in one script it will appear in the other.

answered Oct 5, 2010 at 14:11

Comments

0

Yes, you have a global object in the DOM that both files write variables to. Basically if file1 says:

foo = bar;

then in file2 you can access foo

If you explicitly want to declare a global variable, you can use the window object, which is the global object in a web page:

window.foo = 'bar';

More about global objects: http://www.quirksmode.org/js/this.html

answered Oct 5, 2010 at 14:11

Comments

0

If you think of including javascript files as replacing the with the actual content of the script then of course. If the variable is global, file2 will have access to it.

answered Oct 5, 2010 at 14:11

Comments

0

The only way you can do this is by giving each file its own "namespace".

var File1 = {
 X: 2
};
var File2 = {
 X: 3
};

Just in case this is isn't clear. What I mean is the contents of each file must be wrapped in a named object which will act as a namespace.

answered Oct 5, 2010 at 14:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.