You can provide some basic protection using Object.defineProperty like this:
var o = { a: 5 };
o._protected = {};
o._protected.a = o.a;
Object.defineProperty(o, 'a', {
get: function() { return this._protected.a; },
set: function(value) {
if (value > 0 && value < 5) {
this._protected.a = value;
}
configurable: false
});
This will constrain changes to property a
in this object so they will go through the get (read) / set (update). Of course, in this case the _protected
object can be manipulated but it does require the user to consciously 'hack' it. Attempts to directly change property a
would be under your control.
In this example, an attempt to set o.a = 6 would result in no change to o.a (of course, you could set it to the maximum allowed value in your set function if that were preferable).
You can prevent changes to o.a by not providing a set function.
This can be handy for ensuring properties only get 'valid' values and I've often used it that way.