Friday, May 17, 2024
192
rated 0 times [  196] [ 4]  / answers: 1 / hits: 15717  / 15 Years ago, tue, september 8, 2009, 12:00:00

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


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.


More From » object-literal

 Answers
58

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

[#98735] Thursday, September 3, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pariss

Total Points: 255
Total Questions: 99
Total Answers: 117

Location: Hungary
Member since Wed, Nov 9, 2022
2 Years ago
;