문제

  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.

For example:

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.

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? It attempts to provide the following solution:

  • Some sort of #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

다른 팁

Here's a good read: http://snook.ca/archives/javascript/no-love-for-module-pattern, and another: 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.

(Sorry, I realise this isn't a complete answer, but there's some untampered info for you)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top