If I create an object, such as:
var obj = {
val1: 1,
val2: Math.random()
};
When the object is instantiated, Math.random() is immediately evaluated and the result assigned to obj.val2.
Every future reference to obj.val2 will return this initial random number.
Is there a way to force this function to be re-evaluated each time the object is referenced? So every reference to obj.val2 will re-run Math.random(), yielding a newly generated random number?
You can define a getter, this way every time you access the property you can run a function that returns a new value each time.
var obj = {
val1: 1,
get val2() {
return Math.random();
}
};
console.log(obj.val2)
console.log(obj.val2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With