Private state with prototypes, using weakMap
by ScottRippey
JavaScript
var Person = (function() {
var _ = weakMap();
var Person = function(first, last) {
_(this).firstName = first;
_(this).lastName = last;
}
Person.prototype = {
fullName: function() {
return _(this).firstName + _(this).lastName;
},
firstName: function() {
return _(this).firstName;
}
};
return Person;
})();
function weakMap() {
var instances=[], values=[];
return function(instance, destroy) {
var index = instances.indexOf(instance);
if (destroy) {
// Delete the private state:
instances.splice(index, 1);
return values.splice(index, 1)[0];
} else if (index === -1) {
// Create the private state:
instances.push(instance);
values.push({});
return values[values.length - 1];
} else {
// Return the private state:
return values[index];
}
};
}