Static local variables

joe joeedh at
Mon Aug 10 18:39:06 UTC 2015

Eek, this is even worse than I though.  From the previous discussion:

    If "static" means "shared per-Function-object" or "shared per
activation of the enclosing scope of the
    static's scope", we quickly run into weird behavior. Another
example, on top of Waldemar's:

         function foo() { function nextID() { static s = 0; return
s++; } ... ... }

    Imagine what a programmer who wants nextID to produce unique ids
would think upon discovering
    that it doesn't. What could the bug possibly be? Moving nextID out
to global scope fixes it. Think
    how crazy this is. The function doesn't even refer to anything in
its scope-- yet its scope affects its

IIRC, my code hoists all the way to module scope, so that example
would work as intended.  But that's the problem: it's not at all clear
to me that it *should* work that way.  Even worse, perhaps it *should*
work, but *not* this:

        function foo() { var nextID = function() { static s = 0;
return s++; } ... ... }

eek!  This is even worse than the existential operator in terms of
unintended consequences.

I've been feeling guilty for not sharing my experience with this
feature, since I do use it a lot.  I recently implemented ES6 modules
as a little require.js loader plugin (it only transpiles the module
syntax, since Chrome now has most everything else in ES6), perhaps
I'll write a little plugin for this, too.  Then I can use it in only
the half-dozen or so files that really need it.



More information about the es-discuss mailing list