d4rty d4rty - 7 months ago 23
Javascript Question

Visibility of JavaScript varaibles when using getScript

My webpage consist of multiple javascript files, which I dynamically load via the JQuery instruction

$.getScript(...)
. But I noticed some behaviour which I can't understand.

For example assume
myScript1.js
looks like this:

var a;
var b;

function ab() {
a=1;
b=2;
}


If I now do the following inside
anotherScript.js
, I will get the following logs:

$.getScript("scripts/myScript1.js", function() {
ab();
console.log(a); //prints 1
console.log(b); //prints 2
})


The strange thing, which I don't understand is, the following:
If I do the following inside
oneMoreScript.js
, I will get the same output:

$.getScript("scripts/myScript1.js", function() {
console.log(a); //prints 1
console.log(b); //prints 2
});


Why are the variables in the last code example still declared? I read that every
getScript
instruction is actually an ajax instruction and if no chache is activated (default is none, which is the case), everytime a
getScript
instruction is executed, the desired script will be loaded again from the server and be executed.

Answer

In this code:

var a;
var b;

function ab() {
    a=1;
    b=2;
}

You have two global variables a and b; since they were set once in ab(), they will be accessible with the same values from other code too.