Strict mode in namespace with javascript

Lately, reading a very good book; 'Accessible Javascript' , I discovered the use of the "right" pragma.

“Use strict” seems to be bad practice if it is declared in a global area. The recommended way is to use strict mode directly in each function, for example:

// Non-strict code...

(function(){
  "use strict";

  // Define your library strictly...
})();

// Non-strict code...

Is it possible to define strict mode for the entire namespace instead of defining it in each function? If so, can I have one or two code samples?

Thank.

+5
source share
3 answers

, , , ( squidginess , eval, eval, squidginess), 'd , :

(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...
})();

, foo bar. , , "" ( ):

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

    foo();
})();

... ReferenceError ( - "use strict"):

(function() {
    "use strict";

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

    foo();
})();

... , , - .

, , :

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

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

})(MyModule);

"" MyModule.doSomethingUseful, . , , , , . , .

+5

- "use strict"; .js. .
. js. , .

:

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 = o.Pixel(300, 300);

} // end 

"private". , f 'private' var.

:

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

T.J.Crowder's, - ... -, .

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

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

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

I think this should work too.

0
source

All Articles