Reputation: 15742
is this possible?
We sure know how to emulate private members in javascript:
var Class = (function() {
var _private;
Class = function() {
_private = {};
};
Class.prototype.set = function(name, value) {
_private[name] = value;
};
Class.prototype.get = function(name) {
return _private[name];
};
return Class;
})();
The side effect of this pattern is that when I create two instances:
var instanceOne = new Class();
var instanceTwo = new Class();
then the private property is shared between:
instanceOne.set('test', 'me');
instanceTwo.get('test');
Is there some work around for this problem?
Regards
Upvotes: 2
Views: 832
Reputation: 1074098
The standard way to have "private" members in JavaScript is to use local variables within the constructor and have anything that needs to access them defined as closures over the context of the call to the constructor, like this:
function Class() {
var privateValue = 0;
this.getPrivateValue = function() {
return privateValue;
};
}
Class.prototype.doSomething = function() {
// This function doesn't have access to `privateValue`
// except through `getPrivateValue`, even though
// it's accessible as a member of the instance
};
This has been described by many, probably most famously Douglas Crockford.
Note that this has the repercussion that each instance of Class
gets its own copy of the getPrivateValue
function, because each is a closure over a different call to the constructor (which is why it works). (This doesn't mean all the code of the function is duplicated, however; at least some engines — Google's V8 engine, used in Chrome and elsewhere for instance — allow the same code to be shared by multiple function objects which have different associated contexts.)
(Side note: I haven't used the name private
because it's a reserved word. In ES3, it was a "future reserved word;" in ES5, it's only one in strict mode; details.)
I've used a simple variable above rather than an object to avoid making things look more complex than they are. Here's the way the would apply to your example:
function Class() {
var privateData = {};
this.get = function(name) {
return privateData[name];
};
this.set = function(name, value) {
privateData[name] = value;
};
}
Or if you still want to also have class-wide private data shared across instances:
var Class = function() {
var dataSharedAmongstInstances;
function Class() {
var privateDataForEachInstance = {};
this.get = function(name) {
return privateDataForEachInstance[name];
};
this.set = function(name, value) {
privateDataForEachInstance[name] = value;
};
}
return Class;
})();
Upvotes: 3