0

I have a page with one external script file. Inside this script 3 global objects are used:

var oArticle = new Article();
var oUiManager = new UiManager();
var oController = new Controller();

I was suggested today to put them all into one object, for example inside exercisePage:

var exercisePage = {
    "oArticle": new Article(),
    "oUiManager": new UiManager(),
    "oController": new Controller()
};

What are the benefits of such approach if I'm using only one script file for the page?

4

1 回答 1

2

像这样对对象进行分组只会最大限度地减少全局变量冲突的机会。

如果您包含很多外部库,您需要确保它们都可以正常工作,而不会影响彼此的变量。

也就是说,大多数库都设计得很好,它们不太可能与用户定义的变量发生冲突。

不过,比将它们放在对象中更好,匿名闭包有效

(function(){
  var oArticle = new Article();
  var oUiManager = new UiManager();
  var oController = new Controller();

  // other code that uses these objects
})();
于 2013-11-05T08:32:43.370 回答