4

我正在研究关于 localstorage 的 Dive Into HTML 5 Tutorial,并遇到了这段代码:

function supports_html5_storage() {
  try {
return 'localStorage' in window && window['localStorage'] !== null;
  } catch (e) {
return false;
  }
}

我了解关于return 'localStorage' in window等的部分,但我不明白为什么这里需要 try catch 语句?简单地写下以下内容还不够吗?

function supports_html5_storage(){
return 'localStorage' in window && window['localStorage']!==null;
}

顺便说一句:我确实(有点)知道 try/catch 的目的,我只是想知道我们可能期待什么样的异常?

4

1 回答 1

7

If your browser supports HTML5 storage, there will be a localStorage property on the global window object. If your browser doesn’t support HTML5 storage, the localStorage property will be undefined. Due to an unfortunate bug in older versions of Firefox, this test will raise an exception if cookies are disabled, so the entire test is wrapped in a try..catch statement.

Above text copied from: http://diveintohtml5.info/detect.html#storage

于 2013-01-04T09:36:03.740 回答