A
A
Alexey Yarkov2018-04-03 20:22:21
JavaScript
Alexey Yarkov, 2018-04-03 20:22:21

What method or property should be overridden in the class?

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)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Yarkov, 2018-04-04
@yarkov

Not quite what I wanted, but still decided to leave it like this:

/* @flow */

const storage: Object = {}

class MemoryStorage implements MemoryStorageInterface {
  get length (): number {
    return Object.keys(this.storage).length
  }

  get storage (): Object {
    return storage
  }

  getItem (key: string): string | null {
    return (key in this.storage) ? this.storage[key] : null
  }

  setItem (key: string, value: any): void {
    this.storage[key] = value
  }

  removeItem (key: string) {
    const found = (key in this.storage)
    if (found) {
      delete this.storage[key]
    }
  }

  clear () {
    for (const k in this.storage) {
      delete this.storage[k]
    }
  }

}

export default new MemoryStorage()

A
Archakov Dennis, 2018-04-03
@archakov06

You don't need to redefine anything. You return an instance of the class. You need to create an addon. a method, like getStorage() , that will return ls each time the method is called.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question