What is best practice to get a variable outside of its anonymous function without polluting the global namespace?
A number of possibilities:
Which makes the most sense depends upon how much data you need to share, how widely it needs to be shared, whether the sharing is both ways, etc...
The typical design pattern for exposing global data with the minimum impact on polluting the global namespace is to do something like this:
var JF = JF || {}; // create single global object (if it doesn't already exist)
JF.getMyData = function() {return(xxx);}; // define accessor function
JF.myPublicData = ...;
Then, anywhere in your app, you can call JF.getMyData();
or access JF.myPublicData
.
The idea here is that all public methods (or even data objects) can be hung off the JF object so there's only one new item in the global space. Everything else is inside that one object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With