"use strict"; prepended blindly to scripts in the wild

Brendan Eich brendan at mozilla.com
Wed Sep 8 18:52:11 PDT 2010

On Sep 8, 2010, at 6:34 PM, felix wrote:

> On 9/8/10 17:25, Brendan Eich wrote:
>> On Sep 8, 2010, at 3:25 PM, felix wrote:
>>> in the Names strawman, "private foo" at the top level has the same problem as "use strict" at the top level.  maybe there should be a general way of delimiting a top-level lexical scope, so that pasting js together is still relatively easy?
>> Today, module pattern:
>> (function () {
>>   // "use strict" or private x; here without fear...
>> })();
> that's not quite the same thing since the innards can't introduce new top-level bindings.  you can't just wrap an arbitrary js file in the module wrapper and still have it work.  you have to rewrite it.

That's true, and there's no way around it. But you can't create global variables by assignment in ES5 strict mode. If your code section really needs to create global bindings, even if properly via var and function (never by assignment), then it's likely you don't want "use strict"; at the top of it.

You could "use strict" in each top-level function, but what if you have 930 functions in your code section? Better to use a module pattern and export object for now (more below), and simple modules later.

> I guess the transformation could be automated, though it's a bit more complex than just concatenation.

There's no easy way to support concatenation and "use strict" (or private x). But the "ease" of concatenative programming in JS is an illusion already. Accumulating properties in the global object is a constant source of bugs and confusion. Modern JS libraries minimize their global binding sets.

One nice way to minimize (sorry if this is old hat):

var exports = (function () {
   // everything else here
   return {...};

This enables "use strict" coverage of all the code in the module pattern that returns the exports object. Of course you'd want to prefix "exports", or do something that avoids binding even one global var.


More information about the es-discuss mailing list