Reading Property Attributes

Description

We can retrieve the property descriptor using Object.getOwnPropertyDescriptor() method.

This method accepts two arguments: the object and the name of the property.

The return value is an object with properties for configurable, enumerable, get, and set for accessor properties or configurable, enumerable, writable, and value for data properties.

Example


var book = {};
//w  ww  .  j a v a2s .co m
Object.defineProperties(book, {
      _year: {
         value: 2004
      },
      edition: {
         value: 1
      },
      year: {
         get: function(){
            return this._year;
         },
         set: function(newValue){
            if (newValue > 2004) {
               this._year = newValue;
               this.edition += newValue - 2004;
            }
          }
       }
});

var descriptor = Object.getOwnPropertyDescriptor(book, "_year");
console.log(descriptor.value);          
console.log(descriptor.configurable);   
console.log(typeof descriptor.get);     

var descriptor = Object.getOwnPropertyDescriptor(book, "year");
console.log(descriptor.value);          
console.log(descriptor.enumerable);     
console.log(typeof descriptor.get); 

The code above generates the following result.

Note

The Object.getOwnPropertyDescriptor() method can be used on any object in JavaScript, including DOM and BOM objects.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions