Multiple Global Variables in Javascript -
this isn't specific problem, more theoretical question. there ever reason expose multiple global variables for single javascript application?
i can see using, , use myself, single global variable name object or class containing app can recalled multiple times (example below), can't think of case when additional global variables couldn't replaced object properties.
example exposed variable makes life easier (using closure, couldn't recalled):
var myglobalapp = { init: function (args) {...}, methodone: function () {...}, methodtwo: function () {...}, propertyone: 'string example' }; myglobalapp.init(arg1); myglobalapp.init(arg2);
does know of instance case multiple global variables necessary?
i don't think it's ever strictly necessary have multiple globals - javascript objects can arbitrarily nested, , can used namespaces.
window.awesomemodule = { app: { ... }, util: { ... } };
in fact, if app not made reusable (i.e. it's user-facing), not leak any globals.
(function() { var awesomemodule = { ... }; // whatever want - create dom nodes, bind events, etc // don't bind window })();
a more interesting question whether having multiple globals ever genuinely useful, , i'd depends on development style. example, if @ c# , .net in general, can see entire framework (more or less), namespaces , all, housed beneath top level namespace system
.
of course, if you're going making huge javascript app multiple components, not recommend such nested structure (besides being possibly unwieldy, javascript object attribute lookups have definite runtime cost, add up).
...regardless, though, javascript landscape not well-pruned. simple check global attributes yields around 56 items on machine on empty page (running chrome).
var = 0; (var prop in window) { if (window.hasownproperty(prop)) { i++; } }
so, although can , should minimize our own global usage, js environment stands today (especially when using external libraries) involved proliferation of globals. example: stackoverflow has around 144 total globals.
Comments
Post a Comment