Js code : avoid modules collision

// Create the global symbol "com" if it doesn't exist
// Throw an error if it does exist but is not an object
var com;
if (!com) com = {};
else if (typeof com != "object")
    throw new Error("com already exists and is not an object");

// Repeat the creation and type-checking code for the next level
if (!com.davidflanagan) com.davidflanagan = {}
else if (typeof com.davidflanagan != "object")
    throw new Error("com.davidflanagan already exists and is not an object");

// Throw an error if com.davidflanagan.Class already exists
if (com.davidflanagan.Class)
    throw new Error("com.davidflanagan.Class already exists");

// Otherwise, create and populate the namespace with one big object literal
com.davidflanagan.Class = {
    define: function(data) { /* code here */ },
    provides: function(o, c) { /* code here */ }
};


 

 

Testing the Availability of a Module

var com;  // Declare global symbol before testing for its presence
if (!com || !com.davidflanagan || !com.davidflanagan.Class)
    throw new Error("com/davidflanagan/Class.js has not been loaded");


 

 

 

The best way to structure a module of this sort is to put the code inside an anonymous function that is invoked immediately after being defined:

(function( ) {  // Define an anonymous function.  No name means no global symbol
    // Code goes here
    // Any variables are safely nested within the function,
    // so no global symbols are created.
})( );          // End the function definition and invoke it.
 

 

 

 

 

你可能感兴趣的:(modules)