如何将私有变量添加到此Javascript对象文字片段?

Ada*_*ham 15 javascript object-literal

在MDC找到了这个,但是我想如何添加一个私有变量

var dataset = {
    tables:{
        customers:{
            cols:[ /*here*/ ],
            rows:[ /*here*/ ]
        },
        orders:{
            cols:[ /*here*/ ],
            rows:[ /*here*/ ]
        }
    },
    relations:{
        0:{
            parent:'customers', 
            child:'orders', 
            keyparent:'custid', 
            keychild:'orderid',
            onetomany:true
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在Javascript中理解OOP的方式,如果存在这样的项目,我可以访问dataset.tables.customers.cols [0].
但是,如果我想将私有变量放入客户,那会是什么样子?在运行时错误中
添加var index = 0;结果.

Pet*_*ley 26

没有涉及的函数,你不能拥有"私有"变量.函数是在javascript中引入新范围的唯一方法.

但不要害怕,您可以在正确的位置添加功能,以获得与您的对象的这种功能

var dataset = {
  tables: {
    customers:(function(){
      var privateVar = 'foo';
      return { 
        cols:[ /*here*/ ],
        rows:[ /*here*/ ]
      }
    }()),
    orders:{
      cols:[ /*here*/ ],
      rows:[ /*here*/ ]
    }
  },
  relations: [{
    parent:'customers', 
    child:'orders', 
    keyparent:'custid', 
    keychild:'orderid',
    onetomany:true
  }]
};
Run Code Online (Sandbox Code Playgroud)

但这并没有让我们受益匪浅.这仍然只是一堆文字对象.这些类型的"私有"变量没有任何意义,因为没有方法 - 没有任何实际读取或以其他方式使用我们通过添加函数(闭包)创建的范围中的变量.

但是如果我们有一个方法,那实际上可能会开始变得有用.

var dataset = {
  tables: {
    customers:(function(){
      var privateVar = 'foo';
      return { 
        cols:[ /*here*/ ],
        rows:[ /*here*/ ],
        getPrivateVar: function()
        {
          return privateVar;
        }
      };
    }()),
    orders:{
      cols:[ /*here*/ ],
      rows:[ /*here*/ ]
    }
  },
  relations: [{
    parent:'customers', 
    child:'orders', 
    keyparent:'custid', 
    keychild:'orderid',
    onetomany:true
  }]
};

alert( dataset.tables.customers.getPrivateVar() );
Run Code Online (Sandbox Code Playgroud)


Pet*_*ham 10

JavaScript缺乏您在更严格的语言中获得的访问控制.您可以使用闭包来模拟对象数据的私有访问,但您的示例是一个对象文字 - 一个简单的数据结构 - 而不是一个构造的对象.

它取决于你想要对象做什么 - '私有'成员的常规技术意味着它们只能由成员函数访问,并要求你使用构造函数来创建对象.文字语法用于具有公共数据和功能的数据结构或轻量级对象.

使用私有闭包模式的问题是文字中的字段在公共范围内,但闭包给出的隐私是因为变量是在函数中定义的,因此本地作用域.您可以创建一个克隆文字并添加私有字段的函数,也可以添加一个包含私有数据的公共字段.您还可以将闭包添加为成员,因此创建私有字段,这些字段是方法私有而不是对象私有.

dataset = {
    secretCounter: ( 
      function () {
      var c = 0;
      return function () { return ++c; }
    })(),      
   ...
Run Code Online (Sandbox Code Playgroud)

所以dataset.secretCounter()有一个varable c只对该函数是私有的.