Object.getOwnPropertyDescriptors()

Introduction

How it works ?

Examples

Detailed explanation

Syntax

Parameter

Return Value

Exceptions

Limitations

Common use cases:

Tips and tricks:

Ecmascript specification

See ECMAScript specification

Exercises

Here are a few exercises that can be used to practice using Object.getOwnPropertyDescriptor():

  1. Write a function that copies all the property descriptors from one object to another.
Solution
function copyPropertyDescriptors(source, target) {
  const descriptors = Object.getOwnPropertyDescriptors(source);
  Object.defineProperties(target, descriptors);
}

const source = {
  name: "John",
  age: 30,
};

const target = {};
copyPropertyDescriptors(source, target);

console.log(target.name); // "John"
console.log(target.age); // 30
  1. Write a function that creates a new object with the same properties and property descriptors as another object.
Solution
function cloneObjectWithDescriptors(obj) {
  const clonedObj = Object.create(Object.getPrototypeOf(obj));
  const descriptors = Object.getOwnPropertyDescriptors(obj);
  Object.defineProperties(clonedObj, descriptors);
  return clonedObj;
}

const person = {
  name: "John",
  age: 30,
  get greeting() {
    return `Hello, my name is ${this.name} and I am ${this.age} years old`;
  },
};

const clonedPerson = cloneObjectWithDescriptors(person);
console.log(clonedPerson.greeting); // "Hello, my name is John and I am 30 years old"

This page was updated on -