Using getters and setters Part 3

Here is the final Part 3 post on getters and setters. This is more refined and considered the goto method.

Here, the USD price is pre-defined as usual as price_USD.

The key takeaway is in this line :

const addINRPrice = (product) => Object.defineProperty(product, 'price_INR', INRPriceConverter);

price_INR is defined as a property in the products array of objects by setting it in Object.defineProperty. As you can see, there are 3 arguments to this :

  1. the product, which is the parameter in addINRPrice method.

  2. The other property price_INR which we had declared in the products array explicitly in the first two parts of this blog series, is now dynamically added.

  3. The method that is used to set and get the dynamically added property price_INR.

this.products.map(addINRPrice); adds the price_INR property to each of the objects in the products array.

In AlpineJS store's init() method which does some initialisation, a method INRPriceConverter is defined that has a setter and a getter to convert / return USD or INR values.

Let's see what the setter and getter in INRPriceConverter does.

The getter is straight-forward - return this.price_USD * 83; returns the INR value when the USD value is multiplied by 83.

Now the setter which has a parameter val in this.price_USD = val / 83; - here, val is price_INR (that's added dynamically) and calculated to it's USD value.

Demo : https://anjanesh.s3.amazonaws.com/demo/alpine/alpine-auto-update-variable-method-2.html

0
Subscribe to my newsletter

Read articles from Anjanesh Lekshminarayanan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anjanesh Lekshminarayanan
Anjanesh Lekshminarayanan

I am a web developer from Navi Mumbai working as a consultant for cloudxchange.io. Mainly dealt with LAMP stack, now into Django and trying to learn Laravel and Google Cloud. TensorFlow in the near future. Founder of nerul.in