Given an object obj
, I would like to define a read-only property 'prop'
and set its value to val
. Is this the proper way to do that?
Object.defineProperty( obj, 'prop', { get: function () { return val; } });
The result should be (for val = 'test'
):
obj.prop; // 'test' obj.prop = 'changed'; obj.prop; // still 'test' since it's read-only
This method works btw: http://jsfiddle.net/GHMjN/
I'm just unsure if this is the easiest / smoothest / most proper way to do it...
The below does: document. getElementById("input_field_id"). setAttribute("readonly", true);
Read only means that we can access the value of a property but we can't assign a value to it. When a property does not have a set accessor then it is a read only property. For example in the person class we have a Gender property that has only a get accessor and doesn't have a set accessor.
Use setAttribute() Method to add the readonly attribute to the form input field using JavaScript. setAttribute() Method: This method adds the defined attribute to an element, and gives it the defined value. If the specified attribute already present, then the value is being set or changed.
You can use mapping modifiers to change a readonly property to mutable in TypeScript, e.g. -readonly [Key in keyof Type]: Type[Key] . You can remove the readonly modifier by prefixing the readonly keyword with a minus - .
You could instead use the writable
property of the property descriptor, which prevents the need for a get
accessor:
var obj = {}; Object.defineProperty(obj, "prop", { value: "test", writable: false });
As mentioned in the comments, the writable
option defaults to false
so you can omit it in this case:
Object.defineProperty(obj, "prop", { value: "test" });
This is ECMAScript 5 so won't work in older browsers.
In new browsers or node.js it is possible to use Proxy to create read-only object.
var obj = { prop: 'test' } obj = new Proxy(obj ,{ setProperty: function(target, key, value){ if(target.hasOwnProperty(key)) return target[key]; return target[key] = value; }, get: function(target, key){ return target[key]; }, set: function(target, key, value){ return this.setProperty(target, key, value); }, defineProperty: function (target, key, desc) { return this.setProperty(target, key, desc.value); }, deleteProperty: function(target, key) { return false; } });
You can still assign new properties to that object, and they would be read-only as well.
Example
obj.prop // > 'test' obj.prop = 'changed'; obj.prop // > 'test' // New value obj.myValue = 'foo'; obj.myValue = 'bar'; obj.myValue // > 'foo'
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