I am here playing with the local Storage. And Want it to get or set the value of local storage inside an object. I know the set or get item is the recommended operations for this but somewhere i found that :
LocalStorage can also be set by using : localStorage.myvalue = "something";
And for getting the current value we simply call : localStorage.myvalue;
Now I put this in an object like :
var myObj = {
myval: localStorage.myvalue
}
When i set the value of myObj.myval="somethingAgain"
;
Then this doesn't Works, Normally the objects can be easily set or get by this method,but in this case why it so happens??
The retrieval of the value is working by calling myObj.myval
but why i am not able to set the value here??
So Suggest me where I am Wrong ?
First
localStorage.a = "value";
// create object
var ob = { a: localStorage.a };
console.log(ob.a); // "value"
When you doing things like that:
ob.a = "asfasf"
console.log(ob.a); // "asfasf"
console.log(localStorage.a); "value"
The value don't change because ob.a equal to value, IT NOT A REFERENCE its a VALUE, you get the value by doing localStorage.a!
Working version
var ob = { a: function(value){ return localStorage.a = value; }};
ob.a("value"); // returns "value"
console.log(localStorage.a); // "value"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With