Let's look at an example of why getters (and so are also setters) are so useful.
Let's say you have an AJAX call that you're using via fetch
to retrieve the value of 1 USD in INR. Say we have a script that gets the content of https://open.er-api.com/v6/latest/USD and parse the data to get the USD to INR value.
Now, the time taken to fetch from open.er-api.com is not instant as its a network call to another location, so there will be some delay.
Ideally, the function to fetch the rates would be like this (thanks to open.er-api.com for allowing cross-origin requests).
const get_usd2inr = async () =>
{
return fetch("https://open.er-api.com/v6/latest/USD")
.then(response => response.json())
.then(response =>
{
console.log(response['rates']['INR']);
return response['rates']['INR'];
});
}
Because it needs some time to execute, we need to use await
in an async
function.
let rate = undefined;
document.addEventListener("DOMContentLoaded", async () =>
{
rate = await get_usd2inr();
});
But if you want to assign it immediately to a variable, like inside that of an object :
let obj =
{
usd2inr: rate
}
In 99% of cases, it'll be undefined
as the get_usd2inr
returns a promise, which hasn't yet finished executing and hence obj.usd2inr
remains undefined
.
To get the value of rate
whenever you call for it, return rate
in a getter method of the obj
object. This way, the value of the AJAX called and processed rate
is returned when you call for it later on as in obj.usd2inr
.
let obj =
{
get usd2inr()
{
return rate;
}
}
Here's the full code :
Clicking on the 1st button "click 1" would output undefined in the console where as clicking on the 2nd button "click 2" should output the USD value (83.272106 as of now) in the console.
Here's the demo online: https://anjanesh.s3.amazonaws.com/demo/getter-usd2inr.html