Reputation: 187
I have a question regarding the relative safeness of designing Javascript types that use class static/global variables. For example, suppose we had:
function whatever()
{
if(whatever.initialized === undefined)
{
whatever.global_setting = 1024;
whatever.initialized = true;
}
}
whatever.prototype.get_global_setting = function()
{
return whatever.global_setting;
}
whatever.prototype.set_global_setting = function(setting)
{
whatever.global_setting = setting;
}
Now if only one developer/team were to be using the library then whatever nonsense they decide to do on a class-wide scale wouldn't be such a big issue.
But what if we have scripts from several organizations running in a single webpage (ad partners and such) all of which are accessing the library from the same codebase (eg: "XYZ.com/scripts.js")? Will they all get their own private copy or is there even the slightest possibility that it might be shared? If so, then providing an interface for global settings could lead to some pretty serious problems!
EDIT
Just to be clear, my library is actually defined more along the lines of this:
var whatever =
(
function()
{
"use strict";
function internal_whatever()
{
if(internal_whatever.initialized === undefined)
{
internal_whatever.global_setting = true;
internal_whatever.initialized = true;
}
}
internal_whatever.prototype.get_global_setting = function()
{
return internal_whatever.global_setting;
}
internal_whatever.prototype.set_global_setting = function(setting)
{
internal_whatever.global_setting = setting;
}
return internal_whatever;
}
)();
if(typeof module !== "undefined" && module.hasOwnProperty("exports"))
{
module.exports = whatever;
}
Does that totally mitigate the issue, or are there still some corner-cases?
Upvotes: 0
Views: 49
Reputation: 3726
Well, you could use namespace scope instead of global scope. Like plugins do. Simplified something like this:
;var Modules = (Modules === undefined) ? {} : Modules;
Modules.whatever = {
_nonecares: 1234,
whatever: function(){
return this._nonecares
}
};
console.log(Modules.whatever._nonecares);
This is how the newest jquery does it:
(function(global, factory){
"use strict";
// Pass this if window is not defined yet
})(typeof window !== "undefined" ? window : this, function( window, noGlobal){
"use strict";
// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if( !noGlobal ){
window.jQuery = window.$ = jQuery;
}
return jQuery;
});
Upvotes: 1