5

扩展这个答案,我想知道如何创建属于同一命名空间(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/

4

2 回答 2

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();
于 2013-05-22T22:15:07.930 回答
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 || {});
于 2013-05-22T15:07:28.167 回答