Javascript Object getOwnPropertyDescriptor()

Introduction

To retrieve the property descriptor, use Object.getOwnPropertyDescriptor() method.

This method accepts two arguments:

  • the target object
  • the name of the property.
let book = {};//from  w w  w  . j a  v  a  2s.  c  o m
Object.defineProperties(book, {
    year_: {
        value: 2020
    },

    edition: {
        value: 1
    },

    year: {
        get: function() {
            return this.year_;
        },

        set: function(newValue) {
            if (newValue > 2020) {
                this.year_ = newValue;
                this.edition += newValue - 2020;
            }
        }
    }
});

let descriptor = Object.getOwnPropertyDescriptor(book, "year_");
console.log(descriptor.value); // 2020 
console.log(descriptor.configurable); // false 
console.log(typeof descriptor.get); // "undefined" 

descriptor = Object.getOwnPropertyDescriptor(book, "year");
console.log(descriptor.value); // undefined 
console.log(descriptor.enumerable); // false 
console.log(typeof descriptor.get); // "function" 



PreviousNext

Related