Is it possible to make a javascript object property read-only? I want to set a property that cannot be modified...
+5
A:
It's possible, but expensive. You can do it by having a truly private member variable and then providing an accessor function:
var NiftyThing = function() {
var trulyPrivateVariable;
trulyPrivateVariable = 5; // For instance
this.accessorFunction = function() {
return trulyPrivateVariable;
}
};
That works because the accessor function is a closure over the var. The cost is that each instance has its own copy of the accessor function.
EDIT: Usage:
var n = new NiftyThing();
alert(n.trulyPrivateVariable);
// Alerts "undefined"
alert(n.accessorFunction());
// Alerts "5"
See Private Member Variables in JavaScript for more.
T.J. Crowder
2009-08-24 10:57:34
although, note that accessorFunction can be overwritten by a determined user. Although it won't affect trulyPrivateVariable, it will affect anything that calls accessorFunction.
cobbal
2009-08-24 11:01:50