1

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 ?

2 Answers 2

4

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"];
        }
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Well that was quick. +1
any solution to this problem?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.