let ls = {}
class MemoryStorage {
getItem (name) {
return (name in ls) ? ls[name] : null
}
setItem (name, value) {
ls[name] = value
}
removeItem (name) {
const found = name in ls
if (found) {
delete ls[name]
}
}
clear () {
ls = {}
}
}
const storage = new MemoryStorage()
console.log(Object.keys(window.localStorage)) // выведет массив ключей window.localStorage
console.log(Object.keys(storage)) // выведет пустой массив
UPD:class MemoryStorage {
get length () {
return Object.keys(this).length
}
getItem (name) {
return (name in this) ? this[name] : null
}
setItem (name, value) {
this[name] = value
}
removeItem (name) {
const found = (name in this)
if (found) {
delete this[name]
}
}
clear () {
for (const k in this) {
delete this[k]
}
}
}
const storage = new MemoryStorage()
storage.setItem('getItem', 'getItem') // Переопределяется getItem [КАК ИЗБЕЖАТЬ???]
const item = storage.getItem('getItem') // TypeError: storage.getItem is not a function
console.log('item:', item)
storage.removeItem('getItem')
storage.setItem('test', 'test')
console.log('Length:', storage.length)
console.log(Object.keys(storage))
storage.clear()
console.log(Object.keys(storage))
console.log('Length:', storage.length)