9.3 Retrieving descriptors for properties

9.3.1 Object.getOwnPropertyDescriptor(): retrieving a descriptor for a single property

Consider the following object:

  1. const legoBrick = {
  2. kind: 'Plate 1x3',
  3. color: 'yellow',
  4. get description() {
  5. return `${this.kind} (${this.color})`;
  6. },
  7. };

Let’s first get a descriptor for the data property .color:

  1. assert.deepEqual(
  2. Object.getOwnPropertyDescriptor(legoBrick, 'color'),
  3. {
  4. value: 'yellow',
  5. writable: true,
  6. enumerable: true,
  7. configurable: true,
  8. });

This is what the descriptor for the accessor property .description looks like:

  1. const desc = Object.getOwnPropertyDescriptor.bind(Object);
  2. assert.deepEqual(
  3. Object.getOwnPropertyDescriptor(legoBrick, 'description'),
  4. {
  5. get: desc(legoBrick, 'description').get, // (A)
  6. set: undefined,
  7. enumerable: true,
  8. configurable: true
  9. });

Using the utility function desc() in line A ensures that .deepEqual() works.

9.3.2 Object.getOwnPropertyDescriptors(): retrieving descriptors for all properties of an object

  1. const legoBrick = {
  2. kind: 'Plate 1x3',
  3. color: 'yellow',
  4. get description() {
  5. return `${this.kind} (${this.color})`;
  6. },
  7. };
  8. const desc = Object.getOwnPropertyDescriptor.bind(Object);
  9. assert.deepEqual(
  10. Object.getOwnPropertyDescriptors(legoBrick),
  11. {
  12. kind: {
  13. value: 'Plate 1x3',
  14. writable: true,
  15. enumerable: true,
  16. configurable: true,
  17. },
  18. color: {
  19. value: 'yellow',
  20. writable: true,
  21. enumerable: true,
  22. configurable: true,
  23. },
  24. description: {
  25. get: desc(legoBrick, 'description').get, // (A)
  26. set: undefined,
  27. enumerable: true,
  28. configurable: true,
  29. },
  30. });

Using the helper function desc() in line A ensures that .deepEqual() works.