我应该命名函数和类吗?

时间:2014-06-20 21:18:48

标签: javascript

我一直在阅读一些全球性的恐吓文章,你可以感谢Crockford这个问题。

例如,我有一个我定义为:

的函数
function httpRequest() {}

这是一个非常通用的函数名,可以可能在第三方库中使用。我应该养成将函数附加到app命名空间的习惯吗?

APPNAME.httpRequest() {}

我阅读了谷歌的JavaScript风格指南,他们推荐用于变量,功能和类怎么样?

APPNAME.MyClass = (function () {
  'use strict';

  function MyClass() {}

  MyClass.prototype.myMethod = function () {};

  return MyClass;
}());

编辑: 我们假设我计划与许多其他图书馆合并。

1 个答案:

答案 0 :(得分:2)

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

命名空间也是一种选择,但通常不太理想。

相关问题