Reputation: 245
I have a object like as follows
var obj={
userName:sessionStorage["userName"]
}
1st time if I try to access obj.userName
i am getting undefined, because there is no value in it.
Now if I am getting undefined even after setting the value for it
sessionStorage["userName"]="name";
obj.userName; //undefined
How to solve this ?
Upvotes: 1
Views: 161
Reputation: 59232
You should do this:
sessionStorage["userName"]="name";
obj.userName = sessionStorage["userName"];
obj.userName;//name
Just changing the value of sessionStorage
doesn't reflect the change to the object itself.
In order to change the object, you need to actually change the object.
Upvotes: 0
Reputation: 239473
userName
takes the value of sessionStorage["userName"]
at the time of its creation. Later changes to sessionStorage["userName"]
will not be reflected in userName
.
If you want to get sessionStorage["userName"]
whenever you get value from userName
, then you need to define a getter, like this
Object.defineProperties(obj, {
userName: {
get: function() {
return sessionStorage["userName"];
}
}
});
Upvotes: 4