Object Methods - patrickcole/learning GitHub Wiki

Object Methods

getOwnPropertyDescriptors

Returns all information regarding keys, values and property-methods for a given object

With the often-used Person example:

const person = {
  first_name: 'Patrick',
  last_name: 'Cole',
  get fullName() {
    return `${this.first_name} ${this.last_name}`;
  }
  set specialName(name) {
    this.first_name = name;
  }
}

console.log(person);
// => { first_name: 'Patrick', last_name: 'Cole' }
console.log(person.fullName);
// => 'Patrick Cole'

Notice in the example above when logging person it does not show the get fullName and set specialName property-methods.

When cloning objects with Object.assign(), it will bring over all keys, values and with property-methods, it will bring the values assigned with get fullName as those are defined with this. However, with the set, the value will be undefined.

const imposter = Object.assign({}, person);
console.log(imposter);
/* =>
{
  first_name: 'Patrick',
  last_name: 'Cole',
  fullName: 'Patrick Cole',
  specialName: undefined
}
*/

To resolve this we can use Object.defineProperties along with Object.getOwnPropertyDescriptors:

const twin = Object.defineProperties({}, Object.getOwnPropertyDescriptors(person));


Sources