Advantages of the HTML5 localstorage method?

I use localStorage, and the question came to me:

What is the advantage of using setItem and getItem methods rather than:

  SET ITEM: localStorage.myKey = "myValue";
 GET ITEM: localStorgae.myKey -> returns "myValue"

Are they just helper methods? Good practice?

Just thanks for the curiosity.

+4
source share
2 answers

HTML5 Storage is based on named key / value pairs. You store data based on a named key, then you can retrieve this data using the same key. A named key is a string. Data can be any type of JavaScript-supported type, including strings, booleans, integers, or floats. However, the data is actually stored as a string. If you save and retrieve anything other than strings, you will need to use functions such as parseInt () or parseFloat () to force your extracted data to the expected JavaScript data type.

 interface Storage { getter any getItem(in DOMString key); setter creator void setItem(in DOMString key, in any data); }; 

Calling setItem () with an existing named key will silently overwrite the previous value. Calling getItem () with a key that does not exist will return null, and not throw an exception.

Like other JavaScript objects, you can think of the localStorage object as an associative array. Instead of using the getItem () and setItem () methods, you can simply use square brackets. For example, this piece of code:

 var foo = localStorage.getItem("bar"); // ... localStorage.setItem("bar", foo); 

... could be rewritten instead of using square bracket syntax:

 var foo = localStorage["bar"]; // ... localStorage["bar"] = foo; 
Perhaps this hope .: D

Link: http://diveintohtml5.info/storage.html

+5
source

set / getItem better than an access property for the following reasons:

  • localStorage forces all input to strings, but you can overwrite the set / getItem methods to serialize and deserialize 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 the ECMAScript 5 APIs.

  • You cannot set the length storage key, and you cannot access the 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 
+1
source

Source: https://habr.com/ru/post/1500740/


All Articles