Apr 18, 2017

js object property descriptor

javascript properties has descriptors called property descriptors. You can access property descriptors like this
  
 var person ={
  name: {lastName:'xyz', firstName:'abc'},
  age: 15
 }
 console.log(Object.getOwnPropertyDescriptor(person,'name'));

This should return
  
 {
  value: object, //this could be value for primitives type property
  writable: true, 
  enumerable: true, 
  configurable: true
 }

You can update these descriptors by using Object.defineProperty
   
 Object.defineProperty(person,'age',{value:5});

Updating writable property descriptor to false will make this property read only
   
 Object.defineProperty(person,'age',{writable:false});

After doing this you won't be able to update property value
  
 person.age = 11; // This will throw error as it cannot assign to read only age property

In the following case we are making name property to be read only, but you can still update any of the property of name object as you not changing name property reference
  
 Object.defineProperty(person,'name',{writable:false});
 person.name.lastName = 'xyza'

If you want to prevent this to happen you can use
  
 Object.freeze(person.name);

After this you wont be able to update lastName
  
 person.name.lastName = 'xyzab' // This will throw error as it cannot assign to read only age property

Updating configurable to false will prevent from redefining the property. You will not be able to change enumerable/configurable property descriptor. You will also not be able to delete the property.
  
 Object.defineProperty(person,'age',{configurable:false}); 

Following will throw error
  
 Object.defineProperty(person,'name',{enumerable:false}); //cannot redefine property age
 Object.defineProperty(person,'name',{configurable:false}); //cannot redefine property age
 delete person.age //cannot delete property age

You will still be able to change writable descriptor
  
 Object.defineProperty(person,'age',{writable:false}); 

Updating enumerable to false will prevent this property to be enumerated
    
 Object.defineProperty(person,'age',{enumerable:false}); 

After executing above line you wont be able to see age property in any of the below code
   
 for (var propertyName in person){
    console.log(propertyName + ": " + person[propertyName])
 }
 console.log(Object.keys(person))

  console.log(JSON.stringify(person))  

No comments:

Post a Comment