开发者

"Namespace" collision detection in JavaScript?

Does the JavaScript frameworks which mimics namespaces like jQuery makes some namespace collision detect开发者_运维百科ion ? 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜