Search code examples
jqueryglobal-variablesgetscript

jQuery global variable with getScript


I have this myObject decalred in foo.js, and modifed in bar.js.

And I tried to get the result when getScript is done. However it seems myObject is not a global variable if it is decalred inside jQuery.

Can someone please explain this to me?

foo.js

/*
    // this works fine, but I want to decalre it inside jQuery
    var myObject = {
        str: "hello world",
        num: "123"
    };
*/

$(function() {

    // this makes myObject NOT a global valriable
    var myObject = {
        str: "hello world",
        num: "123"
    };

    alert(myObject.str + " " + myObject.num);

    $.getScript("bar.js", function() {
        alert(myObject.str + " " + myObject.num);
    });
});

bar.js

$(function() {
    myObject = {
        str: "new string",
        num: "999"
    };
});

Solution

  • OK, thanks Arun, but this works... window.myObject

    $(function() {
    
        // global variable defined inside function
        window.myObject = {
            str: "hello world",
            num: "123"
        };
    
        // ...
    });