Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localStorage.prototype is null

I'm trying to extend localStorage w/ the following...

localStorage.prototype.setItem2 = function(key,value) {
    localStorage.setItem(key,value);
}

I'm getting "localStorage.prototype is null." Am I doing this correctly? Thanks!

like image 323
Ian Davis Avatar asked Nov 19 '11 05:11

Ian Davis


People also ask

How can I tell if localStorage is null?

Using the localStorage.getItem() method. The localStorage. getItem() method takes the key as an argument and returns the key's value. if a key doesn't exist it returns the null .

How do you check localStorage is set or not?

To check if a key exists in HTML local storage by using JavaScript, you can use the getItem() method of the localStorage object.

Can we store JSON in localStorage?

localStorage object. We can store more user information in a single key this way. In summary, we can store JavaScript objects in localStorage by first converting them to strings with the JSON. stringify method, then back to objects with the JSON.


3 Answers

localStorage is an instance of the Storage object. Try Storage.prototype.setItem2 or Object.getPrototypeOf(localStorage).setItem2

like image 172
Jim Deville Avatar answered Sep 21 '22 12:09

Jim Deville


You can directly set it by :

localStorage.setItem2 = function(key, value) {
    // do something
}

or use Storage.prototype

Before you do so, make sure you are not overwriting any existing property. This is to prevent any overwriting for future enhancements to the API by the browsers.

like image 32
pradeek Avatar answered Sep 20 '22 12:09

pradeek


LocalStorage and sessionStorage Objects implements from Storage Interface.

You can extend the Storage through prototype.

Storage.prototype.removeItems = function () {
  for(item in arguments) {
    this.removeItem(arguments[item]);
  }
};

Refer to Article: HTML5: Storage APIs

like image 41
Venkat.R Avatar answered Sep 22 '22 12:09

Venkat.R