I'm trying to build a JavaScript constructor which has an array as a property with read-only access:
var Word = function() {
var _occurrences = [];
Object.defineProperties(this, {
"occurrences": {
get: function() {
return _occurrences;
}
},
"addOccurence": {
value: function(occ) {
_occurrences.push(occ);
}
}
});
};
The array itself is a private variable with a get-er pointing to it.
var myWord = new Word();
myWord.addOccurrence(123);
var occ = myWord.occurrences;
All works fine.
myWord.occurrences = [];
Is blocked, as it should be. But surprisingly, this works:
myWord.occurrences.push(321);
Protecting a property keeps it from new assignments, but not from write access through Array methods - even though it is only accessed through a getter. That makes Object.defineProperty() rather pointless to me.
Object.freeze() / Object.seal() is not an option as I need write access for my addOccurrences() method.
Any ideas? Have I overlooked something?