本文介绍了JavaScript命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的应用程序创建一个全局命名空间,在这个命名空间中,我想要其他命名空间:



例如

  Dashboard.Ajax.Post()

Dashboard.RetrieveContent.RefreshSalespersonPerformanceContent();

我还想将它们放在单独的文件中:




  • Ajax.js

  • RetrieveContent.js



但是,我已经尝试使用这种方法,但是它不会工作,因为它是一样的变量名称用于两个单独位置的命名空间。任何人都可以提供其他选择?



谢谢。

解决方案

如果已经创建了您的命名空间对象,则需要确保您不要踩踏。这样的东西可以工作:

 (function(){
//私有vars可以进入


仪表板=仪表板|| {};
Dashboard.Ajax = {
发布:function(){
...
}
};
})();

RetrieveContent 文件将被类似地定义。


I want to create a global namespace for my application and in that namespace I want other namespaces:

E.g.

Dashboard.Ajax.Post()

Dashboard.RetrieveContent.RefreshSalespersonPerformanceContent();

I also want to place them in seperate files:

  • Ajax.js
  • RetrieveContent.js

However I have tried using this method, however it won't work because the same variable name is being used for the namespace in 2 seperate places. Can anyone offer an alternative?

Thanks.

解决方案

You just need to make sure that you don't stomp on your namespace object if it's already been created. Something like this would work:

(function() {
    // private vars can go in here


    Dashboard = Dashboard || {};
    Dashboard.Ajax = {
        Post: function() {
            ...
        }
    };
})();

And the RetrieveContent file would be defined similarly.

这篇关于JavaScript命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 23:35