Get #Amazon #Prime for this #holiday #amazonprime #christmas #2019

#JavaScript - Object.defineProperty(obj, prop, descriptor)

If you start JavaScript in more recent years, you probably haven't seen or used Object.defineProperty().

Object.defineProperty(obj, prop, descriptor)


How does this Object's static method work?

On MDN defineProperty is described as so:

The object on which to define the property.

The name of the property to be defined or modified.

The descriptor for the property being defined or modified.

This method enables addition or modification of a property of an object based on the provided descriptor.


What is a property descriptor?
There are two mutually exclusive types of property descriptors: data descriptors and accessor descriptors. They have to be either one of the two types but not both. 

A data descriptor describes a property that has a value.
An accessor descriptor describes a getter-setter pair of a function.

Descriptors are objects that have the following keys depending on their types:

Both types

// true if the type can be changed and if the property can be deleted
// default to false

// true 
if this property shows up during enumeration of an object's properties ( loop or Object.keys() or Object.entries())
// default to false

Data Descriptor

// the value of the described property 
// default to undefined

// true if the value of the property can be modified with an assignment operator
// default to false


let blog = {};
Object.defineProperty(blog, 'latestArticle', {
  value: 'defineProperty',
  writable: false,
  enumerable: true,
  configurable: true

defineProperty - data descriptor
defineProperty - data descriptor
Object.entries() and Object.keys()
Object.entries() and Object.keys()

Accessor Descriptor

// a function that works as a getter for the property
// when it is called with an object, it assigns `this` in the getter function with that object
// default to undefined

// a function that works as a setter for the property
// when a value is assigned to an object's property, this function is called with the assigned value
// default to undefined

If a descriptor has neither of the type-dependent keys: value, writable, get and set keys, it is treated as a data descriptor.
If a descriptor has both sets of keys: value or writable and get or set keys, an exception is thrown.


let count = 1111;
Object.defineProperty(blog, 'articleCount', {
  get: function() {  return count; },
  set(newValue) {  this.articleCount = newValue; },
  enumerable: true,
  configurable: true

defineProperty - accessor descriptor

Object.entries() and Object.keys()

Object.getOwnPropertyDescriptor / Object.getOwnPropertyDescriptor



You can read more on MDN on how to manage an object's properties such as freezing them.

Thanks for reading!