In JavaScript, you can create an object literal as shown in the listing below:

image

At first sight, it looks like the object cat has two properties with a string and number value. However, it’s much more than that to a JavaScript interpreter. In ES5, the concept of a Property Descriptor was introduced. Before we go ahead and discuss property descriptors, let’s try to answer a few questions:

  1. How do I create a read only property?
  2. How do I make an unenumerable property?
  3. How do I make property not configurable?
  4. How do I determine whether a property is read only?

You can answer all these questions when you understand Property Descriptors.

Let’s consider the code below:

image

Here, your output will be as follows:

As you can see here, there are four characteristics of a property:

  1. Value
  2. Writeable
  3. Enumerable
  4. Configurable

The value holds the data of the property, whereas writeable, enumerable, and configurable describe other characteristics of the property. Let’s take a closer look at each of these characteristics in the rest of this post.

Writable

Whether value of the property can be changed or not is decided by the writable characteristic. If writable is set to false, then the value of the property can’t be changed and JavaScript will ignore any changes in the property value. Consider the code below:

image

You can change the value of the writable, configurable, and enumerable characteristics using Object.defineProperty. We’ll talk more about Object.defineProperty later in this post, but as you see in the code snippet above, we have set the writable to false, thereby changing the value of the name property. JavaScript will ignore the reassignment, and the value of the name property would remain foo.

If you run the code in strict mode, for reassignment of the property value where writable is set to false, JavaScript will throw an exception. Consider the code below:

image

Here, JavaScript is running in strict mode, hence when you reassign the value for the name property, JavaScript will throw an exception as shown below:

The error message here says you cannot assign something to a read only property.  Here, aproperty acts as a read only property if the writable characteristic of the property is set to false.

Read full article on the Infragistics blog

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s