JavaScript,如何在使用单例时保持适当的封装?

时间:2014-10-03 18:59:36

标签: javascript oop namespaces singleton encapsulation

我想开始更好地构建我的JavaScript,这样我就不会污染全局命名空间,也不会像我在本代码审查中所描述的那样实践更好的封装和继承:https://codereview.stackexchange.com/q/64556/42628

所以,举个例子(here is a fiddle of it)......

window.myPage = {
    init:function(){
        //local "Private" declarations
        var gridHandle1 = new myPage.MyGrid();
        gridHandle1.loadGridData();
    },
    MyGrid: function(){
        /* local "Private" declarations */
        var dataLoadTimes = 0;
        var gridDrawn = true;
        $('#debug').append('grid is drawn<br>');

        //This needs to be a public method because
        //other functions need to reload the grid
        //at various times. So I will use "this."
        //instead of "var".  "var" would make it a
        //private method.
        this.loadGridData = function() {
            dataLoadTimes = dataLoadTimes+1;
            $('#debug').append('grid data has been loaded '+dataLoadTimes+' times<br>');
        };

        this.loadGridData();
    }
};

myPage.init();
// console.log(gridHandle1); // <--- fails, GOOD, it's not in the global namespace
// console.log(gridDrawn); // <--- fails, GOOD, it's not in the global namespace

我理解这里发生的一切,我喜欢它,因为&#34; loadGridData&#34;只涉及&#34; MyGrid&#34;,它没有任何业务,它自己的功能在&#34; MyGrid&#34;之外,这将破坏封装。但这样做需要这条线......

var gridHandle1 = new myPage.MyGrid();

很酷,它允许我创建这样的网格......

var gridHandle1 = new myPage.MyGrid();
var gridHandle2 = new myPage.MyGrid();
var gridHandle3 = new myPage.MyGrid();

但在这种情况下,我不需要很多网格。我只需要一个。所以我的问题是,我如何调整这段代码,以便一切工作相同,但作为单身人士,不使用&#34;类&#34;方法并使用构造函数实例化一个对象?

1 个答案:

答案 0 :(得分:0)

有几种方法可以实现这一目标并最终归结为偏好。

就个人而言,我这样编码:(没有jquery - 我不使用它)

var myPage = {
  ua: {}
}

$(function() {
   myPage.mainLayout = new dhtmlXLayoutObject(document.body, "2U");
   myPage.mainTabBar = myPage.mainLayout.cells("b").attachTabbar();
   myPage.initTab(myPage.mainTabBar);
});


myPage.initTab=function(tb){  
   tb.xyz();
}: 


myPage.ua.load=function(id){
    myPage.ua.innerLayout = myPage.mainTabBar.tabs(id).attachLayout("1C");
    myPage.ua.grid        = myPage.ua.innerLayout.cells("a").attachGrid();
}

myPage.ua.search = function() {
    myPage.ua.grid.clearAndLoad([theUrl], "json");
};

有时我会定义ua,有时我会将所有内容都绑定到myPgae