0

Say i have a JS file that stores a singular object. In another JS script i need to access this object. Can I use .getScript to do this or is there another way? When i try to use .getScript the variables i set outside of the scope and update in the getScript scope do not update.

user3259121
  • 3
  • 1
  • 2
  • Can you change the script to define a function, and then call the function? – Barmar Jan 31 '14 at 22:44
  • 1
    Can you give us some code samples of how you are trying to use this? If I'm understanding you correctly, what you are asking should be possible. – samanime Jan 31 '14 at 22:44
  • If not, you have to use a global variable. It will be in scope of both scripts. – Barmar Jan 31 '14 at 22:44
  • Yes, you can do this. Note however that whatever is defined within the script you are getting will be defined globally, so if you have something that is defined locally using the same name, you'll have to access it as a property of `window`. – Kevin B Jan 31 '14 at 22:45
  • Why not store the object as json in a json file and use $.getJSON? – forsvunnet Jan 31 '14 at 22:45

1 Answers1

0

Given the following html:

<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script>
    var external = false;
    $.getScript('test.js', function(){
        console.log(external);
    });
</script>

And the following script in test.js:

var external = {
    my:'object'
};

The log will show {my:'object'}

forsvunnet
  • 1,238
  • 10
  • 17
  • I'll try to clarify what i meant. If you have the above code var external = false; $.getScript('test.js', function(){ external = testJsObject; }); console.log(external); and then in the test.js var testJsObject = true; would the console log true, showing that the external variable was changed and then can be used. – user3259121 Jan 31 '14 at 22:53
  • Any variable defined at root in test.js will be available at root once the script is loaded. The code in your comment works – forsvunnet Jan 31 '14 at 23:03
  • Doesn't seem to be working when I try it. If i try it with an integer value and set it to 0 prior to the getScript code and set it to another value inside the getScript code it doesnt get updated. – user3259121 Jan 31 '14 at 23:08
  • It sounds to me like you're having scope issues. It's hard to say more without seeing the code. – forsvunnet Jan 31 '14 at 23:51