我一直在阅读一些全局 panic 文章,你可以感谢 Crockford 提出这个问题。
例如,我定义了一个函数:
function httpRequest() {}
这是一个非常通用的函数名称,可以在第三方库中使用。我应该养成将函数附加到应用程序命名空间的习惯吗?
APPNAME.httpRequest() {}
我通读了 Google 的 JavaScript 样式指南,他们建议对变量使用此方法,那么函数和类呢?
APPNAME.MyClass = (function () {
'use strict';
function MyClass() {}
MyClass.prototype.myMethod = function () {};
return MyClass;
}());
编辑: 假设我计划与许多其他库结合。
最佳答案
JavaScript 变量是闭包作用域的。因此您始终可以使用 IIFE 来封装它们:
(function(){
function httpRequest() { /* */ }
httpRequest(...);
})()
//httpRequest is not defined here unless it was defined above the block
您还可以将内容导出到全局命名空间
var httpUtils = (function(){
return whatever; // whatever is exported, the other variables are internal
})()
创建封装此类行为并公开某些行为的对象称为模块模式。
您可以使用模块加载器来管理您的模块。一个例子是 RequireJS.
require(["httpUtils","logger",function(http,log){
http.request(...); // uses from other module
log(..); // use other module
return { }; // the return values can be used in other modules, require by file name
// or explicit configuration
});
命名空间也是一种选择,但通常不太理想。
关于javascript - 我应该命名函数和类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24335796/