I've been working on converting one of my mid-sized JavaScript APIs from using a lot of global variables and functions to a more organized structure similar to the namespace encapsulation seen in libraries like jQuery. I've decided to implement this using anonymous functions.
Here is a snippet of the code:
(function(window, undefined) {
var MyLib = (function() {
var AbortProgram = true;
function DisplayAbortProgram() { alert('AbortProgram inside=' + AbortProgram); }
return { AbortProgram: AbortProgram, DisplayAbortProgram: DisplayAbortProgram }
} ())
window.MyLib = MyLib;
})(window);
MyLib.AbortProgram = false;
alert('AbortProgram outside=' + MyLib.AbortProgram);
MyLib.DisplayAbortProgram();
Upon running the code, the value of AbortProgram outside the function is false while inside it remains true. This has led me to question why this behavior is occurring. It seems likely that the issue lies in the return statement, which may be returning the value of DisplayAbortProgram rather than a reference to it. As JavaScript returns values for primitive types and not references, objects are passed by reference instead.
After research, it appears that there might not be a way to return a reference to the boolean variable directly. Therefore, I will need to implement a function called SetAbortProgram(value) to handle this situation.