2017-06-19 38 views
4

我想知道如何讀取什麼類型的存儲對象是「這個」? 比方說,你有這樣的功能:如何在JavaScript中閱讀什麼類型的存儲是'this'?

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

現在,您將看到的sessionStorage或localStorage的數據。但是如何在JS代碼中獲取這些信息呢?我試過

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

它只返回[object Storage],但這顯然不是我所搜索的。
我查看了存儲類型的可用方法,但沒有返回真實類型。有沒有獲取這些信息的方法?

+0

您是否嘗試過'this === sessionStorage'和'this === localStorage'? – sbking

+0

我不認爲有任何「正確」的方式來檢查這在JavaScript中。 JavaScript中只有一個通用的'存儲'類型,它並不公開與其連接的底層瀏覽器存儲系統。你當然可以檢查'this == sessionStorage'之類的東西,但我認爲沒有更好的解決方案......但是很好的問題。 –

回答

2

不幸的是,存儲對象不包含公開可用於區分它們是否提供本地或會話存儲的任何屬性。我只是通過谷歌Chrome瀏覽器中的the HTML storage specificationmuch of the source code used to implement it來確認這一點。

您唯一的選擇是比較Storage對象的身份與其全局定義。你可能想直接做到這一點,而不是打擾包裝它的方法。

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' 

由於每一個這些都是存儲對象的特殊剛剛情況下,有沒有確定哪些變量每個實例已經被分配到的一般方式。

相關問題