如何将私有变量添加到此Javascript对象文字片段? [英] How to add private variable to this Javascript object literal snippet?

查看:97
本文介绍了如何将私有变量添加到此Javascript对象文字片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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
        }
    }
}

我理解的方式在Javascript中的OOP,如果存在这样的项目,我可以访问dataset.tables.customers.cols [0]。

但是如果我想将私有变量放入客户中,那会是什么样子?$
添加 var index = 0; 会导致运行时错误。

The way I understand OOP in Javascript, I'd have access to dataset.tables.customers.cols[0] if such an item exists.
But if I wanted to place a private variable into customers, what would that look like?
Adding var index = 0; results in a runtime error.

推荐答案

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

You can't have "private" variables without a function involved. Functions are the only way to introduce a new scope in javascript.

但是从不担心,你可以在正确的位置添加函数来获得这个对象的一些功能

But never fear, you can add functions in the right place to gain this sort of functionality with your object

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
  }]
};

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

But this doesn't gain us much. This is still mostly just a bunch of literal objects. These types of "Private" variables have zero meaning since there are no methods - nothing that would actually read or otherwise use the variables in the scope we created by adding a function (a closure).

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

But if we had a method, that might actually start to become useful.

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() );

这篇关于如何将私有变量添加到此Javascript对象文字片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆