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

I want to know how you can read what type of storage object is "this"? Say you got this function:

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

You will now see the data in sessionStorage or localStorage. But how to get this information in JS code? I tried

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

It only returns [object Storage], but this is obviously not what I was looking for.
I looked at the available storage type methods, but no one returned the real type. Is there any way to get this information?

+4
source share
2 answers

, , , , . HTML Google Chrome, .

- . , .

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

, .

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

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

Storage, , .

+2

Source: https://habr.com/ru/post/1679648/


All Articles