Javascript – Problem accessing global javascript variables

globaljavascriptjquerywindow

My application has something like the following structure

window.object1;
window.object2;
$(document).ready(function() {
   window.object1 = new type1object();
});

function type1object() {
   //lots of code
   this.property = 'property';
   window.object2 = new type2object();
}

function type2object() {
   //lots of code
   this.property = new type3object();
}

function type3object() {
   //lots of code
   console.log(window.object1);
   this.property = window.object1.property;
}

The problem is that whenever I try to access window.object1 from anywhere other than the document ready callback it comes back as undefined, this is even though when I inspect the DOM window.object1 is defined exactly as I expect it to be.

I've tried doing the same as above but using simple global variables instead (i.e. var object1 instead of window.object1) … Tried declaring initial dummy values for object1 and object2 in various places… but run up against the same problem.

Does anyone know why I can't access my global variables globally?

Best Answer

You have to make sure you are evaluating window.object1 after initiating it. That is, in your case, only after document.ready finished executing

If you look at this example below you can see that at click both are initialized.

<html>
    <body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
    <script>        
        $(document).ready(function() {
           window.object1 = new type1object();
           window.object2 = new type2object();
           //console.log(window.object1);
        });

        $(document).click(function(){
            console.log(window.object1);
            console.log(window.object2);            
        });

        function type1object() {
        }

        function type2object() {
        }

    </script>