简体   繁体   English

JavaScript中的“命名空间”冲突检测?

[英]“Namespace” collision detection in JavaScript?

Does the JavaScript frameworks which mimics namespaces like jQuery makes some namespace collision detection ? 模仿jQuery之类的名称空间的JavaScript框架是否进行某些名称空间冲突检测? 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: JavaScript名称空间通常使用对象和闭包来模仿,并且通常使用自调用函数进行初始化:

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. 此外,我发现在实际实现对数据结构或名称空间的任何更改之前进行检查很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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