Javascript comparing 2 checks for localStorage

2019-02-15 03:11发布

问题:

I saw this in the diveintohtml5 website. This is how they check to see if localstorage is supported on the browser.

return 'localStorage' in window && window['localStorage'] !== null;

Would this be the same as just doing?

return window.localStorage != undefined

回答1:

1

return 'localStorage' in window && window['localStorage'] !== null;

This returns true if the window object contains a property with the name localStorage and the value of that property is not null.


2

return window.localStorage != undefined

This returns true if the window object contains a propety with the name localStorage and the value of that property is not undefined or null (I am assuming that the global property undefined holds the value undefined)



回答2:

Same result anyhow since if window.localStorage is undefined you will both get false. And if window.localStorage is null you will both get false because undefined == null.

However, I prefer using !! just because it's the fastest way to convert to a boolean and how useful is localStorage if it's false, null, undefined, '', NaN or 0?

return !!window.localStorage;

Edit One caveat, they are not exactly the same since if you set window.localStorage to undefined the first would report it as true



回答3:

You can use Modernizr (1.1 or later) to detect support for HTML5 local storage.

if (Modernizr.localstorage) {
  // window.localStorage is available
} else {
  // no support for local storage
}


回答4:

I wish you to recommend the following function:

function getLocalStorage(){
   if (typeof localStorage == “object”){
      return localStorage;
   } else if (typeof globalStorage == “object”){
      return globalStorage[location.host];
   } else {
      throw new Error(“Local storage not available.”);
   }
}
  1. First check will be enough to make sure localStorage is availabe
  2. Some browsers still don't support local storage, but global storage. It has the same function set, but has some differences comparing with localStorga
  3. If none of storages is supported, throw exception.

If you want to read about global storage, compare it with local storage, Look at "JavaScript for Web Developers", chapter 19. It describes client local storages, comparing it with cookies.