简体   繁体   中英

“Namespace” collision detection in JavaScript?

Does the JavaScript frameworks which mimics namespaces like jQuery makes some namespace collision detection ? If not should I manage it myself ?

If yes what prevents such framework to detect such collision themselves ?

JavaScript namespaces are normally mimicked by using objects and closures, and often initialized with a self-invoking function:

var myNamespace = (function () {
   var _name = 'Bob';

   return {
      somePublicMethod: function () {
         return 'Hello, ' + _name;
      }
   };
})();

alert(myNamespace.somePublicMethod());

Unfortunately if you redefine the namespace variable, there's no warning for that. What you could really do is to check if the namespace variable has already been defined, and throw an exception or raise an error if it was:

if (typeof myNamespace !== 'undefined') {
    var myNamespace = (function () {
        // ...
    })();
}
else {
    throw new Error("Whoops! myNamespace already exists.");
}

Consider coming up with a development standard where entire team agrees on how you will call your namespaces. Also I found it useful reviewing any changes to data structure or namespaces before actually implementing them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM