views:

34

answers:

5

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
    });
A: 

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

Aaron Hathaway
A: 

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

Peter Kruithof
A: 

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.

methodin
A: 

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.

ChaosPandion
+2  A: 

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.

lincolnk