Reputation: 53
I've been using localStorage and a question came to me:
Which is the advantage using setItem
and getItem
methods rather than:
SET ITEM : localStorage.myKey = "myValue"; GET ITEM : localStorgae.myKey --> returns "myValue"
Are they just helper methods then? Good practices?
Just about curiosity thanks.
Upvotes: 4
Views: 1481
Reputation: 115910
set
/getItem
are better than property-access for the following reasons:
localStorage
coerces all its input into strings, but you can overwrite the set
/getItem
methods to perform serialization and deserialization to support types other than strings:
var basicSetItem = localStorage.setItem;
localStorage.setItem = function(key, val) {
basicSetItem.call(localStorage, key, JSON.stringify(val));
}
var basicGetItem = localStorage.getItem;
localStorage.getItem = function(key) {
return JSON.parse(basicGetItem.call(localStorage, key));
}
You cannot achieve an equivalent effect for all storage property values using ECMAScript 5 APIs.
You cannot set the storage key length
, and you cannot access the keys getItem
, setItem
, or removeItem
without using function access:
localStoage.length = "foo"; // does not work
localStoage.setItem("length", "foo"); // works
var bar = localStoage.setItem; // gets the `setItem` function
var bar = localStorage.getItem("setItem"); // gets the value stored in the `setItem` key
Upvotes: 1
Reputation: 411
HTML5 Storage is based on named key/value pairs. You store data based on a named key, then you can retrieve that data with the same key. The named key is a string. The data can be any type supported by JavaScript, including strings, Booleans, integers, or floats. However, the data is actually stored as a string. If you are storing and retrieving anything other than strings, you will need to use functions like parseInt() or parseFloat() to coerce your retrieved data into the expected JavaScript datatype.
interface Storage {
getter any getItem(in DOMString key);
setter creator void setItem(in DOMString key, in any data);
};
Calling setItem() with a named key that already exists will silently overwrite the previous value. Calling getItem() with a non-existent key will return null rather than throw an exception.
Like other JavaScript objects, you can treat the localStorage object as an associative array. Instead of using the getItem() and setItem() methods, you can simply use square brackets. For example, this snippet of code:
var foo = localStorage.getItem("bar");
// ...
localStorage.setItem("bar", foo);
…could be rewritten to use square bracket syntax instead:
var foo = localStorage["bar"];
// ...
localStorage["bar"] = foo;
Maybe this hope. :D
Reference: http://diveintohtml5.info/storage.html
Upvotes: 5