判断JS全局变量是否存在

var a = undefined或者var a相当于是给window对象添加了a属性,但是未赋值,即window.a === undefined为true

if (typeof localStorage !== 'undefined') {
  // 此时访问localStorage不会出现引用错误
}

或者

if ('localStorage' in self) { // 浏览器端全局处window/this/self三者彼此全等
  // 此时访问 localStorage 绝对不会出现引用错误
}

注意二者的区别:

var a // 或 var a = undefined
'a' in self // true
typeof a // 'undefined'
  • var a = undefined或者var a相当于是给window对象添加了a属性,但是未赋值,即window.a === undefined为true
  • typeof a就是返回其变量类型,未赋值或者声明类型为undefined的变量,其类型就是undefined

Was this helpful?

0 / 0

发表评论 0

Your email address will not be published. Required fields are marked *