Using getters and setters Part 3

Using getters and setters Part 3

Defining a property to an object using Object.defineProperty()

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