Java Reference
In-Depth Information
So far, we've just set properties by assignment, which only allows you to set the value
attribute of the property. It's also possible to set each of the property attributes by using a
property descriptor. For example, the following object has a property name :
var don = { color: "purple" }
The property descriptor for this property might look like this:
{ value: "purple", writable: true, enumerable: true,
configurable: true }
We've already seen how to add more properties by assignment:
leo.color = "blue";
The disadvantage with this is that it can only be used to set the value attribute of the prop-
erty. Any property set by assignment will have attributes of writable , enumerable ,
and configurable set as true (note that these are the exact opposite of the default
values for those attributes).
Getting and Setting Property Descriptors
The Object() function has a number of methods for getting and defining property
descriptors.
We
can
see
these
values
using
the
Ob-
ject.getOwnPropertyDescriptor() method:
Object.getOwnPropertyDescriptor(leo,'color');
<< {"configurable": true, "enumerable": true, "value":
"blue",
"writable": true}
We can add properties to an object using the Object.defineProperty() method.
This provides more fine-grained control when adding new properties as it allows each at-
tribute to be set. The first argument is the object to which you want to add the property,
followed by a property descriptor containing the attributes you want to set. Any attributes
left out will take the default values:
Search WWH ::




Custom Search