How to add private variable to this Javascript object literal snippet?

后端 未结 3 755
后悔当初
后悔当初 2020-12-14 10:25

Found this at MDC but how if I\'d wanted to add a private variable to the

var dataset = {
    tables:{
        customers:{
            cols:[ /*here*/ ],
            


        
3条回答
  •  忘掉有多难
    2020-12-14 11:06

    Private variables in javascript are done using the var keyword inside a closure. Only priviliged methods and attributes can access it. Here's the way to do it:

    function dataset()
    {
    var private_stuff = 10; // private
    this.foo = new function() { alert(private_stuff); } // priviliged
    return {
        tables:{
            customers:{
                    cols:[  ],
                    rows:[  ]
            },
            orders:{
                    cols:[  ],
                    rows:[  ]
            }
        },
        relations:{
            0:{
                    parent:'customers', 
                    child:'orders', 
                    keyparent:'custid', 
                    keychild:'orderid',
                    onetomany:true
            }
        }
    }; // public
    }
    
    var d = new dataset;
    alert(d.foo());
    

提交回复
热议问题