Recently, while reading a very good book; ‘Maintainable Javascript’, I discovered the use of “use strict” pragma.
The “use strict” seems to be a bad practice if it is declared in the global scope. The recommended way is to use the strict mode directly in each function like this:
// Non-strict code...
(function(){
"use strict";
// Define your library strictly...
})();
// Non-strict code...
Is it possible to define the strict mode to an entire namespace instead of defining it in each function? If yes, can I have one or two samples of code?
Thank you.
Strict mode applies to the execution context in which it’s declared and all of the contexts that context contains (with some squidginess around contexts created via
eval, but avoid usingevaland you avoid the squidginess), so usually you’d use the module pattern to apply it to all your code:In the above, strict mode applies not only to the anonymous function, but to
fooandbaras well. So for instance, where this code would “work” (create a global variable via The Horror of Implicit Globals):…this code fails with a
ReferenceError(the only change is the"use strict"):…because one of the many useful things that strict mode does is get rid of the horror of implicit globals.
Here’s another example, where we export a function that runs in strict mode even when called from non-strict code:
“Loose” code can call
MyModule.doSomethingUseful, which always runs in strict mode. The upshot being that you can apply strict mode to your code without requiring that everyone using your code also use it. Very handy, that.