【问题标题】:js - avoiding namespace conflictjs - 避免命名空间冲突
【发布时间】:2016-02-03 19:58:34
【问题描述】:

到目前为止,我只参与了相对较小的项目(而且大部分是单独的),但这次我必须与其他程序员合作......基本上是因为我必须非常仔细地规划网站的结构以避免花费数小时调试代码。

在这一点上,我想按以下方式进行。我将我的代码划分为模块并将每个模块存储在一个单独的文件中,该文件位于一个对象(或一个函数)内,具有一个虚构的名称(lzheA、lzheB、lzheC 等),以避免在是否使用同名对象时发生冲突另一段代码。加载文档时,我声明了一个变量(一个对象),用作应用程序的主命名空间。对象的属性是我之前定义的模块。

// file BI.lib.js
var lzheA = {
    foo: function() {

    },
    bar: function() {

    },
}

// file BI.init.js
function lzheK() {
    BI.loadPage();
}

// file BI.loadPage.js
function lzheC() {
    var result = document.getElementById('result');
    result.innerHTML = "that worked";
}

// and so on
var lzheA,lzheB,lzheD,lzheE,lzheF,lzheG,lzheH,lzheI,lzheJ;

// doing the following when the document is loaded
var BI = {
    lib: lzheA,
    menu: lzheB,
    loadPage: lzheC,
    customScripts: lzheD,
    _index: lzheE,
    _briefs: lzheF,
    _shop: lzheG,
    _cases: lzheH,
    _blog: lzheI,
    _contacts: lzheJ,
    init: lzheK,
}

BI.init();

https://jsfiddle.net/vwc2og57/2/

问题...这种构建方式值得一试还是因为缺乏经验而错过了什么?尽管每个模块只使用了两次,但在声明变量并将其分配给属性时,模块的虚构名称会让您感到困惑吗?

【问题讨论】:

    标签: javascript namespaces modularization


    【解决方案1】:

    当您想在 Javascript 中模块化应用程序时,我认为命名空间是一个不错的选择。但我以不同的方式声明它们

    var myModule = myModule || {}; // This will allow to use the module in other places, declaring more than one specificComponent in other js file for example
    myModule.specificComponent = (function(){
    
       // Private things
       var myVar = {};
    
       var init = function() {
           // Code
       };
    
       return {
           init: init // Public Stuff
       };
    
    })();
    

    如果你想调用init方法,你可以这样调用它

    myModule.specificComponent.init();
    

    通过这种方法,我保证模块不会被另一个地方的另一个声明覆盖,并且我可以将内部组件声明到我的命名空间中。 此外,仅在返回块中公开您想要的内容的技巧将使您的组件更安全,并且您将以一种漂亮的方式封装您的代码。

    希望对你有帮助

    【讨论】:

    • 谢谢,您的变体看起来更干净了。 :)
    猜你喜欢
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 2010-09-20
    相关资源
    最近更新 更多