JavaScript is essentially a data structure that stores key-value pairs, but unlike maps and dictionaries, JavaScript objects are highly configurable.

When an object is created and properties are added to that object, each property has a default property descriptor associated with it. A property descriptor is a javascript object that contains some information about the corresponding property, such as value.

Object.getOwnPropertyDescriptor

To get the property descriptor of a property, you can use the static method Object.getOwnPropertyDescriptor of Object.

1
Object.getOwnPropertyDescriptor(obj, prop);

The object returned by Object.getOwnPropertyDescriptor is the property descriptor, and the property descriptor contains the following properties to describe the object properties associated with it.

  • value : the current value of the property
  • writable : indicates whether the assignment of a value to a property is allowed
  • enumerable: indicates whether the property is enumerable. true means that the property is enumerable, then the property will appear in for in and for of loops or in object.keys.
  • configurable: indicates whether the property is configurable, true means that the user has permission to change the value in the property descriptor of the property, such as the values of writable and enumerable, false means that it is not configurable and has no permission.

Object.defineProperty

You can define a new property for an object or update the descriptor of an existing property by using Object.defineProperty.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var myObj = {
    p1: 1,
    p2: 2
};

Object.defineProperty(myObj, "p1", {
    writable: false
});

// TypeError: Cannot assign to read only property "p1" of object
myObj.p1 = 2;