简体   繁体   中英

Strict mode in a namespace with Javascript

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 using eval and you avoid the squidginess), so usually you'd use the module pattern to apply it to all your code:

(function() {
    "use strict";

    function foo() {
    }

    function bar() {
    }

    // ...presumably code hooking up `foo` and `bar` to events
    // or otherwise using them -- or of course, you could export
    // them from the scope...
})();

In the above, strict mode applies not only to the anonymous function, but to foo and bar as well. So for instance, where this code would "work" (create a global variable via The Horror of Implicit Globals ):

(function() {
    function foo() {
        someNameThatIsntDefined = 42; // Blech, creates implicit global
    }

    foo();
})();

... this code fails with a ReferenceError (the only change is the "use strict" ):

(function() {
    "use strict";

    function foo() {
        someNameThatIsntDefined = 42; // Throws ReferenceError
    }

    foo();
})();

...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:

var MyModule;
MyModule = MyModule || {};
(function(mod) {
    "use strict";

    mod.doSomethingUseful = doSomethingUseful;
    function doSomethingUseful() {
        // ...
    }

})(MyModule);

"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.

First way is when you put "use strict"; pragma at first line of .js file. So EVERYTHING in that file will be strictly evaluated.
There is nothing inherently wrong with that. Sooner or later all browsers will make 'old js code' deprecated. Only real drawback might be potentially breaking old code if you use it.

Second way might be an object like this:

var contName = new function () {
"use strict";


this.tmp;   // public temp var
var tmp;    // private tmp, propagate thru all!


var f = this;   // to call contName.functions when this = html or other object 
var o = this;   // to create objects.

f.rnd = function rnd (range) {
    return Math.floor(Math.random() * range);
};


    function private1 () {     // can be called only inside of contName

     var x = tmp;   // can see all outer private vars
     this.tmp;    // !== outer this.tmp

    var y = this.rnd(x);    // will not work
    var y = f.rnd(x);    // work
    }


o.Pixel = function (x, y, z, col) {
    this.x = x || 0;
    this.y = y || 0;
    this.z = z || 0;
    this.color = col || 0;
};

tmp = new o.Pixel(300, 300);

} // end 

That code allows you to have "private" variables. Note that f as also a 'private' var.

Usage is simple:

var rvar = contName.rnd(5);
var obj = new contName.Pixel(300, 300)

Third way might be TJCrowder's, fourth is Doug Crockford's ... These are just different ways for emulating something that's not yet officially present in a language.

var Module = (function() {
    "use strict";

    var f = function() {
        // do stuff
    }

    return {  // return your namespace
        "myModuleFunction": f
    }
})();

I think this should work too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM