I have this code here:
var Person = (function() {
var name;
var PersonConstructor = function(n) {
name = n;
};
PersonConstructor.prototype.getName = function() {
return name;
};
return PersonConstructor;
})();
var people = [];
var person1 = new Person("Foo");
var person2 = new Person("Bar");
alert(person1.getName()); // I want it to be Foo
people.push(person1);
people.push(person2);
I got the idea of emulating classes from here.. But of course, I neglected the fact that the private variable var name; is also a static variable. Since this is tripping my current efforts I would like to know if there is a way to keep the private behaviour in this example but avoid the static one?
There is no “private” when working with prototypes.
It should be noted there is no value in private state, avoid it like the plague. Closures are ugly and expensive.
However if you insist on being delusional and want private state badly then
You can store state in a closure
Note this is highly inefficient and has little benefit.
Alternatively you can store state in a weakmap
WeakMapbrowser support is non-existant so emulate it using pd.Name