Data properties
Description
There are two types of properties: data properties and accessor properties.
Data Properties
Data properties contain a data value. Values are read from and written to this value.
Data properties have four attributes describing their behavior:
- Configurable - Indicates if the property can be redefined by removing the property via delete, changing the property's attributes, or changing the property into an accessor property. Default to true.
- Enumerable - Indicates if the property will be returned in a for-in loop. Default to true.
- Writable - Indicates if the property's value is changable. Default to true.
- Value - Contains the actual data value for the property. Default to undefined.
Example
When a property is explicitly added to an object, Configurable,Enumerable, and Writable are all set to true while the Value attribute is set to the assigned value.
var person = {
name: "XML"
};
The property name
is created.
Value attribute is set to "XML", and any changes to that value are stored in this location.
Change attributes
To change any of the default property attributes, you must use .defineProperty() method.
This method accepts three arguments:
- the object on which the property should be added or modified,
- the name of the property, and
- a descriptor object.
The properties on the descriptor object match the attribute names: configurable, enumerable, writable, and value.
var person = {};
Object.defineProperty(person, "name", {
writable: false,//w ww. j a v a 2s . c om
value: "XML"
});
console.log(person.name); //"XML"
person.name = "CSS";
console.log(person.name); //"XML"
The code above marks name
property as read-only.
The code above generates the following result.
Example 2
The following code creates a nonconfigurable property.
var person = {};
Object.defineProperty(person, "name", {
configurable: false,// w ww . j a va 2 s. c om
value: "XML"
});
console.log(person.name); //"XML"
delete person.name;
console.log(person.name); //"XML"
The code above generates the following result.
configurable
We cannot delete a non-configurable property from the object.
Once a property has been defined as nonconfigurable, it cannot become configurable again.
var person = {};
/*w ww . j av a 2s .c o m*/
Object.defineProperty(person, "name", {
configurable: false,
value: "XML"
});
//throws an error
//Object.defineProperty(person, "name", {
// configurable: true,
// value: "XML"
//});
When you are using Object.defineProperty(), the values for configurable, enumerable, and writable default to false unless otherwise specified.