Home > Back-end >  Javascript: How reload an object to update with new value
Javascript: How reload an object to update with new value

Time:09-27

I just got this query/question while writing QUnits. I am not sure it is possible.

How to reload/update an object or how to make an object statically dynamic ?

> var rollNum = 459;
undefined
> var classObj = { studentId : rollNum };
undefined
> classObj
{ studentId: 459 }
> rollNum = 125 ;
125
> classObj
{ studentId: 459 }
>

The behaviour I am expecting here is as, classObj now should load studentId as 125 because as per my object definition rollNum updated with 125.

Current JS behaviour as per my understanding, the moment interpreter starts evaluating, it takes the value of the variable and creating the reference in the memory and the connection between JS object and variable which provided value is gone.

And, I want that connection to be persisted always, once Object defined I want to preserve the definition and whenever I try to access the object, I want to JS interpreter to read the updated/current value of the variable in the memory then store it in the object before returning it.

is this behaviour possible ?

Thank you.

CodePudding user response:

You can use a getter:

var classObj = {
  get studentId() {
    return rollNum;
  },
}

It's a function that gets called whenever studentId gets accessed.

var rollNum = 459;
var classObj = { get studentId() { return rollNum;} };
console.log(classObj);
rollNum = 125 ;
console.log(classObj);

  • Related