0

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

2 Answers 2

1

Since you declared the variable inside a function, it is local to the function. What you can do is declare the variable outside but assign the value inside the jQuery ready handler

foo.js

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

var myObject;
$(function() {

    // this makes myObject NOT a global valriable
    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"
    };
});

Demo: Plunker

Sign up to request clarification or add additional context in comments.

2 Comments

So...the variables inside the 2 jQuery functions (from 2 js files in my example) are NOT in the same scope, is that right?
@user1643156 yes... depending on how the variable is declared
0

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

$(function() {

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

    // ...
});

2 Comments

that is the same as declaring it outside
@ArunPJohny yes they have the same scope but as I stated in my question... I want the variable to be declared inside jQuery.

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.