Is there a good way to define real private variable in dojo?
In dojo 1.7/1.8, I have found 2 ways to define private variable, but both of them are static private(shared by all instances of the class)
1.use anonymous immediate function:
define([
'dojo/_base/declare'], function(declare) {
'use strict';
return declare('test.Class2', null, (function(){
var a = 1;
return {
constructor: function(){
console.log('constructor');
},
geta: function(){
return a;
},
seta: function(v){
a = v;
}
};
})());
});
2.Define the private variable in the module definition.
define([
'dojo/_base/declare'], function(declare) {
'use strict';
var a = 1;
return declare('test.Class1', null, {
constructor: function(){
console.log('constructor');
},
geta: function(){
return a;
},
seta: function(v){
a = v;
}
});
});
Assuming I understand the question correctly, I don't think there is any good ways.
According to the Dojo Style Guid, private variables and methods should be marked by preceding underscore (eg. _myPrivateProperty or _myPrivateMethod()). However, this is just convention and does not make them private; they can still be accessed outside of the class.
You can create private static variables as you've already stated. The other route is to create variables within the class methods, these will only be visible within the scope of the enclosing braces (as already suggested by Paul Kunze in his answer). You could then pass them around the class in function parameters. However, I'm guessing that is not what you are looking for.
It might be possible to do something clever with a static object and each class instance accessing it's own object property. However, this would not be unusual and complicated. I'd advise sticking to the standard of using underscored-properties to mark variable that you consider private.
You can include private variables ... but EVERYTHING must be within the constructor.
The downside to this approach is you would need to explicly perform any inheritance restricting the value of the 'declare' function to using the dojo loader.
How about declaring the required private members inside the constructor?
I'm not sure if this works as I don't define my classes using dojo. Let me know if it worked please.
The dojo documentation has an example where it declares a private class outside of the main declare that is being returned.
http://dojotoolkit.org/reference-guide/1.9/dojo/_base/declare.html#dojo-base-declare
A private class may not be the best solution but at least it provides true privacy.