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
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:
This has been described by many, probably most famously Douglas Crockford.
Note that this has the repercussion that each instance of
Classgets its own copy of thegetPrivateValuefunction, 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
privatebecause 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:
Or if you still want to also have class-wide private data shared across instances: