What are getters and setters in JavaScript

In JavaScript, you may have heard of getters and setters. Let’s take a look at what these things are.

First, a setter is used to set the value of a property. A setter gets called each time the value of the property is changed. In other words, it executes a function for each time a property used inside the setter function is changed. Take a look at the following code:

image

In the object foo, the setter cal will be called each time the property a is changed. As an output, you will get 13 printed. While creating a setter, you need to follow these rules:

  • A setter name could be either string or number.
  • A setter must have exactly one input parameter.
  • There should be only one setter with the same identifier in an object
  • You can remove a setter using the delete operator

For other examples of a setter, let’s take a look at the following code:

image

For the above code snippet as output, Hello Jason will be printed. You can also add the setter to an existing object using Object.defineProperty. Let’s say that you have an object foo:

image

Now to add a setter for the existing object foo , use Object.defineProperty.

image

Read full article on the Infragistics blog

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 )

Connecting to %s

Create a website or blog at WordPress.com