Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force functions in an object to be evaluated each time the object is referenced?

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?

like image 771
Ryan Griggs Avatar asked Mar 07 '23 00:03

Ryan Griggs


1 Answers

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)
like image 188
XCS Avatar answered Mar 17 '23 00:03

XCS