您如何读取 JavaScript 中 'this' 的存储类型?

How can you read what type of Storage is 'this' in JavaScript?

我想知道您如何读取存储对象的类型"this"? 假设你有这个功能:

Storage.prototype.typeOf=function(){return this;}

现在您将在sessionStorage 或localStorage 中看到数据。但是如何在JS代码中获取这些信息呢?我试过了

Storage.prototype.typeOf=function(){
    var x=this;
    alert(this)
}

它 returns 只是 [object Storage] 但这显然不是我搜索的内容。
我查看了存储类型的可用方法,但 none 返回了真实类型。有获取这些信息的方法吗?

由于只有两种类型的存储对象,您可以明确地检查它们。

Storage.prototype.typeOf = function() {
  if (this === window.localStorage) {
    return 'localStorage';
  }
  return 'sessionStorage';
};

console.log(localStorage.typeOf());   // 'localStorage'
console.log(sessionStorage.typeOf()); // 'sessionStorage'

由于这些中的每一个都只是 Storage 对象的特殊实例,因此没有一种通用的方法来确定每个实例已分配给哪个变量。

遗憾的是,存储对象公开任何可用于区分它们是提供本地存储还是会话存储的属性。我刚刚在 Google Chrome 中通读了 the HTML storage specification and much of the source code used to implement it 以确认这一点。

您唯一的选择是将存储对象的标识与其全局定义进行比较。您可能只想直接执行此操作,而不必费心将其包装在方法中。

if (someStorage === window.localStorage) {
  // ...
} else if (someStorage === window.sessionStorage) {
  // ...
}