Getting and Setting Property Descriptors in JavaScript (Part 2)

in #javascript7 years ago

In the previous post, I discussed how to get property descriptors. Now, I am going to tell you how to define a property with a desired property descriptor.

But first, let's see why we would want to do this. Defining properties with property descriptors lets you fine-tune the attributes of the property:

  • You can define the enumerability of the property. If the property is enumerable, it will be listed in a for .. in loop or other iteration mechanisms, such as Object.keys. (I don't mean to say the for .. in loop and Object.keys return the same set of properties. No, they have an important difference. The for .. in loop iterates over all properties, whether own or inherited, while Object.keys returns only own properties.)
  • If a property is configurable, you can change its definition or even delete it. Otherwise, these actions are not possible.
  • For data properties, the writable attribute determines if a value can be assigned to the property. If this flag is set to false, assigning a value to the property will have no effect.
  • For accessor properties, get and set attributes determine whether the property is readable and writable, respectively.

Defining properties is carried out with Object.defineProperty and Object.defineProperties functions which will be presented in the next post.


Related Posts

Sort:  

You should also focus on writable=false behavior for non-primitives, i.e. ordinary objects. I believe a lot of people might think, that this freeze entirely the value against any change which is wrong. Still, for objects, we are able to assign new properties.

Thank you. That's a good point. The property is not writable, but its value, which is an object, can have its own properties changed.

Simply explained. Easy to understand. Thank you

Property discriptors explained very well in a short and Crips way.
Thank you @ghasemkiani.
Found this to be really informative.😊

Your post is very important to me because I did not know about this before, thank you

I am the really learning of your content.I have understood property it is enumerable for...in..Thank you sharing valuable information today.I like this .

This is very useful for defining the properties, very good for java learners.

I agree with you to be your friend

This post has received a 10.25 % upvote from @buildawhale thanks to: @ghasemkiani. Send at least 1 SBD to @buildawhale with a post link in the memo field for a portion of the next vote.

To support our daily curation initiative, please vote on my owner, @themarkymark, as a Steem Witness

Coin Marketplace

STEEM 0.21
TRX 0.14
JST 0.030
BTC 69812.20
ETH 3376.99
USDT 1.00
SBD 2.78