Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get or Set localStorage Value inside Object

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 ?

like image 467
ashbuilds Avatar asked Feb 16 '14 14:02

ashbuilds


1 Answers

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"
like image 108
Farkhat Mikhalko Avatar answered Sep 23 '22 22:09

Farkhat Mikhalko