JavaScript自执行匿名模块

how*_*his 5 javascript

扩展这个答案我想知道如何创建属于同一命名空间(PROJECT)的新模块.

A.init(); -- will become --> PROJECT.A.init();
Run Code Online (Sandbox Code Playgroud)

模块

(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();
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/sKBNA/

Ber*_*rgi 2

只需将附加名称空间插入属性链即可:

\n\n
// create top namespace\nwindow.PROJECT = window.PROJECT || {};\n\n// stays the same\n(function( A, $, undefined ) {\n    A.init = function() {\n        console.log( "A init" );\n    };\n// except for the last line:\n}( window.PROJECT.A = window.PROJECT.A || {}, jQuery ));\n\n// same for the B (sub)namespace:\n(function( B, $, undefined ) {\n    \xe2\x80\xa6  \n}( window.PROJECT.B = window.PROJECT.B || {}, jQuery ));\n\n// and of course add it at the invocations:\nPROJECT.A.init();\nPROJECT.B.init();\n
Run Code Online (Sandbox Code Playgroud)\n