Question

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 ?

Was it helpful?

Solution 2

This seems like it could be accomplished with this following small adjustment.

Update:

Seemed too long for you, shorthand better?

var myObj = {
    myval: function(val){ 
        return (typeof (val) === 'undefined' ? localStorage.myvalue : localStorage.myvalue=val);
    }
}

Than calling it like this to set

myObj.myval("Add this");

or to get

myObj.myval();

Fiddle: http://jsfiddle.net/4WsNx/

Hope this helps.

OTHER TIPS

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"

You could use the Object.prototype.__defineGetter__() and Object.prototype.__defineSetter__().

Or use the get and set operators.

But remember that those are not supported in older browsers!

Your concret problem is that you defined a primitive as attribute to the localStorage-object and not and object as an attribute to the localStorage so you do not have a reference but only a value.

A Solution could be to define the whole localStorage as attribute like this:

var obj = { store: localStorage };
obj.store.setItem('key','a value');
obj.store.getItem('key');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top