简体   繁体   English

JavaScript模块模式/组织/子模块

[英]JavaScript module pattern / organization / sub-modules

  1. I would like to know what's the difference (advantages/disadvantages) between the following patterns. 我想知道以下模式之间的区别(优点/缺点)。
  2. How can I create sub modules based on the module pattern? 如何根据模块模式创建子模块?

My goal is to have my js organized into multiple files that are lazy loaded but have one namespace. 我的目标是将我的js组织成多个 延迟加载但具有一个命名空间的文件。

For example: 例如:

SO.global (global.js) SO.global.registration (registration.js) <- load SO.global(global.js)SO.global.registration(registration.js)< - load

var SO = function(){

    var CONSTANT = 'Z';

    function createX(){
      alert("create X");
    }

    function getY(){
       alert("get Y");
    }
    return{
      create:createX,
      get:getY
    }
}();

//SO.createX(); 
//SO.getY();

VS. VS.

var SO = (function() {

    var CONSTANT = 'Z';

    function createX(){
      alert("create X");
    }

    function getY(){
       alert("get Y");
    }

    return {
      create:createX,
      get:getY
    }

} ());

Have you considered Require.JS ? 你考虑过Require.JS吗? It attempts to provide the following solution: 它试图提供以下解决方案:

  • Some sort of #include/import/require 某种#include / import / require
  • ability to load nested dependencies 加载嵌套依赖项的能力
  • ease of use for developer but then backed by an optimization tool that helps deployment 易于开发人员使用,但后来有一个有助于部署的优化工具

Require.JS implements the Module/Asynchronous Definition spec defined by Common.JS Require.JS实现了Common.JS 定义模块/异步定义规范

Here's a good read: http://snook.ca/archives/javascript/no-love-for-module-pattern , and another: http://lamb.cc/blog/category/javascript/ 这是一个很好的阅读: http//snook.ca/archives/javascript/no-love-for-module-pattern ,另一个: http//lamb.cc/blog/category/javascript/

YUI uses it avidly, as do I, I haven't found any situations where I was restricted by it, and it nicely integrates with the YUI dependency loader for custom Modules. YUI使用它,就像我一样,我没有发现任何我被它限制的情况,它很好地与自定义模块的YUI依赖加载器集成。

(Sorry, I realise this isn't a complete answer, but there's some untampered info for you) (对不起,我意识到这不是一个完整的答案,但有一些未被篡改的信息给你)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM