简体   繁体   English

使用Javascript的命名空间中的严格模式

[英]Strict mode in a namespace with Javascript

Recently, while reading a very good book; 最近,在阅读一本非常好的书的同时; 'Maintainable Javascript' , I discovered the use of "use strict" pragma. 在“可维护的Javascript”中 ,我发现了“严格使用”用法的用法。

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: 严格模式适用于声明了它的执行上下文以及该上下文包含的所有上下文(在通过eval创建的上下文周围具有一定的鱿鱼性,但避免使用eval并避免了鱿鱼性),因此通常您将使用模块模式来将其应用于所有代码:

(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. 在上面,严格模式不仅适用于匿名函数,还适用于foobar 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" ): ... 代码失败,并出现ReferenceError (唯一的更改是"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. “松散”代码可以调用MyModule.doSomethingUseful ,该代码始终在严格模式下运行。 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"; 第一种方法是当您放置"use strict"; pragma at first line of .js file. .js文件第一行的编译指示。 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. 迟早所有浏览器都会弃用“旧js代码”。 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); tmp =新o.Pixel(300,300);

} // end 

That code allows you to have "private" variables. 该代码使您可以拥有“私有”变量。 Note that f as also a 'private' var. 请注意,f也是“私有”变量。

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. 第三种可能是TJCrowder的方法,第四种是Doug Crockford的方法...这些只是模仿某种语言中尚未正式出现的东西的不同方法。

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

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

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

I think this should work too. 我认为这也应该起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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