Is it possible to make a javascript object property read-only? I want to set a property that cannot be modified...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With