Sorry if the answer has already been given, but I did not find a suitable answer here.
I started writing my modular style javascript code recently and I have a question regarding how the module variable area works.
The following code gives me a contradictory answer.
I have a module called Base that declares two strings and an array. It also has a fetchData function that uses the jQuery getJSON shortcut to set these variables with server data. Unfortunately, when I request Base string1 or string2, I get undefined. I understand that this is probably due to the fact that I set two functions in depth for my values ββ(inside the AJAX callback and inside fetchData), and the scope limits this to seeing Base.string1 and Base.string2.
However, when I look at Base.array1 from outside the module, it installs the corresponding data that I pulled from the server, even if it is installed from the same area as the lines.
Here is the code:
namespace.Base = (function(){ var string1, string2, array1 = []; function fetchData(){ $.getJSON('backendScript.php', function(data){ string1 = data.string1; string2 = data.string2; arrayCount = data.arr.length; for(var i = 0; i<arrayCount; i++){ array1[i] = data.arr[i]; } }) } return{ fetchData: fetchData, string1: string1, string2: string2, array1: array1 } })();
If i change
string1 = data.string1;
to
namespace.Base.string1 = data.string1;
It works as I want.
So my question is: why is array1 set correctly when it is set from the same area as strings?
Also, what is the tool for setting module level variables from module functions without having to specify a global path (e.g. namespace.Base.string1)?
source share