JavaScript自执行匿名模块

时间:2013-05-22 15:03:03

标签: javascript

扩展此answer我想知道如何创建属于同一命名空间(PROJECT)的新模块。

A.init(); -- will become --> PROJECT.A.init();

模块

(function( A, $, undefined ) {
    A.init = function() {
        console.log( "A init" );
    };   
}( window.A = window.A || {}, jQuery ));

(function( B, $, undefined ) {
    B.init = function() {
        console.log( "B init" );
    };   
}( window.B = window.B || {}, jQuery ));

A.init();
B.init();

http://jsfiddle.net/sKBNA/

2 个答案:

答案 0 :(得分:2)

只需将其他名称空间插入属性链:

// create top namespace
window.PROJECT = window.PROJECT || {};

// stays the same
(function( A, $, undefined ) {
    A.init = function() {
        console.log( "A init" );
    };
// except for the last line:
}( window.PROJECT.A = window.PROJECT.A || {}, jQuery ));

// same for the B (sub)namespace:
(function( B, $, undefined ) {
    …  
}( window.PROJECT.B = window.PROJECT.B || {}, jQuery ));

// and of course add it at the invocations:
PROJECT.A.init();
PROJECT.B.init();

答案 1 :(得分:1)

只需将对象添加到全局命名空间,将对象文字或函数分配给该命名空间。

window.PROJECT = {};
(function($,window,undefined) {
    var A = {
        init : function() { ... }
    }
    window.PROJECT.A = A;
})(jQuery, window);
PROJECT.A.init();

或者,您可以将模块中的值返回到PROJECT对象。

window.PROJECT = {};
PROJECT.A = (function($, window, undefined) {
    var A = {
        init : function() { ... }
    }
    return A;
})(jQuery,window);

同样,您可以将对象返回到全局变量。

var PROJECT = (function($, window, undefined) {
    var A = {
        init : function() { ... }
    }
    var B = {
        init : function() { ... }
    }
    return { A : A, B : B };
})(jQuery,window);

附加基于OP提到的先前答案,扩展全局命名空间对象。这实际上是通过前一个答案实现的。

var PROJECT = (function(window, undefined) {
    // Private var
    var container,
    // Class constructor
    Example = function() {
    }
    Example.prototype = {
    },
    // Object literal
    A = { 
        init : function() {
            container = new Example();
        }
        // Expose or reflect other methods using private instance of Example
    }
    return { A : A };
})(window);

进一步扩展PROJECT,如前面的例子所示

(function(window, PROJECT, undefined) {
     // Private vars
     ...
     // Any other non exposed code
     ...
     PROJECT.B = {
         init : function() { ... }
     }
     // Make sure PROJECT is attached to window if it is empty object
     if (typeof window.PROJECT === 'undefined')
         window.PROJECT = PROJECT;
})(window, window.PROJECT || {});