On Aug 28, 6:56*am, rocketeer <java...@sbcglobal.netwrote:
I've a set of Javascript classes that maintain state. *For example,
gm.js might be:
var GroupManager { groups: {} };
Over time I add new groups to the list:
GroupManager.groups[key] = myGroup;
One approach is to put a declaration at the start of the file in the
appropriate scope (global here) and conditionally assign it a value:
var groupManager = groupManager || {groups: {}};
So groupManager is a global variable referencing an object that holds
whatever (provided you are aware that any time groupManager evaluates
to a falsey value it will be assigned a reference to the object
literal on the right hand side of the || expression).
Declaring a variable with var can't alter the value of an existing
variable.
Oh, by convention only constructors or constants start with a capital
letter, hence groupManager (or GROUPMANAGER for constants, but I don't
use that). :-)
If I include another Javascript file that also includes a reference to
include gm.js, or do this through an Ajax call, this new loading of
gm.js overwrites my existing GroupManager variable and I lose all my
accumulated data.
So I thought I could do
if(!GroupManager) { *GroupManager = { groups: {} }; }
If GroupManager has not be declared or initialised some other way,
that is a syntax error. If you include var to declare GroupManager,
it is essentially the same as the suggestion above does, i.e.
if (!groupManager) { var groupManager = { groups: {} }; }
is essentially the same as:
var groupManager = groupManager || {groups: {}};
But the GroupManager so instantiated lives only within the if()
block.
That is an incorrect conclusion, there is no block scope in
javascript.
*And to include an initial var GroupManager simply kills state.
Only if you unconditionally assign a value, the declaration by itself
never changes the value per ECMA-262.
Are there any techniques for allowing multiple includes of a
Javascript file while detecting a previous include, allowing me to
preserve any existing variables?
I don't think detecting script file includes is a suitable strategy,
you want to detect whether the variable already has a value and if so,
leave it alone and if not, initialise it.
A declaration with conditional assignment does just that.
--
Rob