To change the default property attributes, use the Object.defineProperty()
method.
This method accepts three arguments:
The properties on the descriptor object match the attribute names:
You can set one or all of these values to change the corresponding attribute values.
For example:
let person = {};// www . j a va 2s .c o m Object.defineProperty(person, "name", { writable: false, value: "HTML" }); console.log(person.name); // "HTML" person.name = "Javascript"; console.log(person.name); // "HTML"
This example creates a property called name with a value of "HTML" that is read-only.
The value of this property can't be changed.
Any attempts to assign a new value are ignored in non-strict mode.
In strict mode, an error is thrown when an attempt is made to change the value of a read-only property.
The following code create a non-configurable property.
let person = {};/*from w w w.j a v a2 s . com*/ Object.defineProperty(person, "name", { configurable: false, value: "HTML" }); console.log(person.name); // "HTML" delete person.name; console.log(person.name); // "HTML"
Here, setting configurable to false means that the property cannot be removed from the object.
Calling delete on the property has no effect in non-strict mode.
It throws an error in strict mode.
Additionally, once a property has been defined as nonconfigurable
, it cannot become configurable again.
Any attempt to call Object.defineProperty()
and change any attribute other than writable causes an error:
let person = {};//from w w w. j av a 2 s . c o m Object.defineProperty(person, "name", { configurable: false, value: "HTML" }); // Throws an error Object.defineProperty(person, "name", { configurable: true, value: "HTML" });
When you are using Object.defineProperty()
, the values for configurable, enumerable, and writable default to false unless otherwise specified.