I have a global var that is updated later on in my program, and a previous variable set that that global var uses the original referenced value.
To illustrate,
var testVar = 1;
var hash = {
test : {
testGetVar : {opacity: testVar},
testGetVarFn : function(){ return {opacity: testVar}; }
}
}
testVar = 2;
console.log(hash.test.testGetVar.opacity); // returns 1
console.log(hash.test.testGetVarFn().opacity); //returns 2
Would someone clarify the proper way to do this?
Let’s say if I had 10 objects in hash that uses testVar, would I have to write fn to get the updated value?
EDIT:
I’ve changed some requirements and made my example to specific to my cause.
Here’s getter/setter methods, but doesn’t work.
var testVar = new Field("123");
function Field(val){
this.value = val;
}
Field.prototype = {
get value(){
return this._value;
},
set value(val){
this._value = val;
}
};
var hash = {
test : {
testGetVar : {opacity: testVar.value} ,
testGetVarFn : function(){ return testVar.value; }
}
}
testVar.value = "abc";
console.log(hash.test.testGetVar.opacity); // returns 123
console.log(hash.test.testGetVarFn()); //returns abc
My assumption is that since the get method called when creating the hash, it stores the reference to that value at that time, thus will never return the updated value
You could turn testVar into an object, because objects are passed by reference in js, this way you would not need to call a function to get the latest value: