javascript - 我应该命名函数和类吗?

标签 javascript

我一直在阅读一些全局 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/

相关文章:

javascript - 严格平等比较

javascript - 数组的 Foreach 循环,通过 AJAX 查询获得

javascript - 将此数组转换为带下划线的对象

javascript - 为什么这个 react 引导模式没有正确响应?

javascript - 如何避免这种情况? Yslow -> "This page has 5 external stylesheets. Try combining them into one."

javascript - 为什么我的 Ramda dropRepeats 函数在这里不起作用?

javascript - 使用Phonegap上传文件: File Transfer Error: request body stream exhausted

javascript - jQuery 捕获按下某个键时的鼠标移动

javascript - 我如何获取链接内容(innerHTML)并将其添加到其他链接作为标题

javascript - 将数据从 VueJS 插件传递到 VueJS 组件