JavaScript的命名空间架构

时间:2012-01-27 19:17:27

标签: javascript jquery

我来自Java世界。在Java中有一些包,例如“com.mycompany.billing”和包内的类,例如“BillProcessor”。我工作的公司正在开始一个新项目,我需要决定一个好的命名空间架构。我正在考虑用Java来预测它是如何完成的,例如,有一个名为“com.mycompany.billing”的命名空间和一个像“BillProcessor.js”这样的文件中的类。此外,单元测试至关重要,因此我需要这样一种易于单元测试的结构。

有人可以建议一个好方法吗?


我认为我想出了一个很好的解决方案,请指教。举个例子,我会制作一个结算页面。共有4个文件:

$ {root} /billing.html - 包含信用卡名称的输入框

$ {root} /js/com/mycompany/common/common.js - 初始化日志记录和错误处理

$ {root} /js/com/mycompany/common/Url.js - 用于执行AJAX调用的类

$ {root} /js/com/mycompany/aproject/billing.js - 初始化结算页面上的内容

例如,common.js包含:

var com_mycompany_common_common = function() {

    function log(message) {
        console.log((new Date()) + ': ' + message);
    }

    function init() {
        window.onerror = function(message) {
            log('Unhandled error: ' + message);
        }
    }

    return {
        log: log,
        init: init
    }
 } ();

 $(document).ready(function() {
      try {
           com_mycompany_common_common.init();
      } catch (e) {
           console.log('Error during initialization: ' + e);
      }
});

Url.js:

function com_mycompany_common_Url(url) {    
    this.url = url;
}

com_mycompany_common_Url.prototype.addParameter(name, value) {
    this.url += '?' + name + '=' + value;
}

com_mycompany_common_Url.prototype.ajax() {
    com_mycompany_common_common.log('Send ajax to: ' + this.url);
}

billing.js

var com_mycompany_aproject_billing = function() {

    function init() {
        $('#submitButton').click(function() {
            Url url = new com_mycompany_common_Url('http://bla.com/process/billing');
            var creditCardName = $('#ccName').val();
            url.addParameter('name', creditCardName);
            url.ajax();
        }
    }

    return {init: init};
} ();

$(document).ready(function() {
      try {
           com_mycompany_aproject_billing.init();
      } catch (e) {
           console.log('Error during initialization: ' + e);
      }
});

billing.html

<!DOCTYPE html>

<html>
    <head>
        <title>Billing</title>
    </head>
    <body>
        Enter name on credit card: <input type="text" id="ccName" /><br><br>
        <button id="submitButton">Submit Payment</button>

        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript" src="js/com/mycompany/common/common.js"></script>
        <script type="text/javascript" src="js/com/mycompany/common/Url.js"></script>
        <script type="text/javascript" src="js/com/mycompany/aproject/billing.js"></script>
    </body>
</html>

2 个答案:

答案 0 :(得分:2)

大多数时候,人们使用Object Literal模式在JavaScript中实现名称间距。

更多信息:http://msdn.microsoft.com/en-us/scriptjunkie/gg578608

您可以像这样“嵌套”命名空间:

var MyCompany = MyCompany || {};
MyCompany.Billing = MyCompany.Billing || {};
// etc...

另一篇ScriptJunkie文章涵盖了一些命名空间:http://msdn.microsoft.com/en-us/scriptjunkie/hh377172.aspx

答案 1 :(得分:0)