[英]Strict mode in a namespace with Javascript
最近,在阅读一本非常好的书的同时; 在“可维护的Javascript”中 ,我发现了“严格使用”用法的用法。
如果在全局范围内声明“严格使用”,则似乎是一种不良做法。 推荐的方法是在每个函数中直接使用严格模式,如下所示:
// Non-strict code...
(function(){
"use strict";
// Define your library strictly...
})();
// Non-strict 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...
})();
在上面,严格模式不仅适用于匿名函数,还适用于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
,该代码始终在严格模式下运行。 其结果是,你可以采取严格的方式对你的代码,而无需使用您的代码也使用它要求每一个人。 非常方便。
第一种方法是当您放置"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
该代码使您可以拥有“私有”变量。 请注意,f也是“私有”变量。
用法很简单:
var rvar = contName.rnd(5);
var obj = new contName.Pixel(300, 300)
第三种可能是TJCrowder的方法,第四种是Doug Crockford的方法...这些只是模仿某种语言中尚未正式出现的东西的不同方法。
var Module = (function() {
"use strict";
var f = function() {
// do stuff
}
return { // return your namespace
"myModuleFunction": f
}
})();
我认为这也应该起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.