I am wondering how to access the native sessionStorage scope from within my custom methods.
My example:
https://jsfiddle.net/3mc7ao7j/1/
At line 3 I would like to be able to proxy through to my native sessionStorage
after perform my mutation on the data.
How do I access that scope again though? I know I can just call:
sessionStorage.setItem()
But that simply works because it is globally available and it feels wrong to do that. Mainly because I would also want to know how to do this without an object that is not globally available so I can learn how to proxy other objects.
Some
window
objects likelocation
are read-only, it can be useful to create abstractions over them or make use of DI for testability.sessionStorage
is supposed to be used as is. Usually no abstractions over it are needed. If its functionality should be extended or modified, a custom class can be created. It can implement Storage interface or have its own.The use of
Proxy
is unjustified here. It is slow and restricts the code from being used in ES5 environments.Custom class or object can just wrap original
sessionStorage
methods. Since Storage API is small, wrapper class results in ~20 lines of code:sessionStorage
object is exotic. Although it inherits fromStorage
,Storage
is not a constructor, andsessionStorage
methods should be bound tosessionStorage
directly, so it's not possible to make it work just withCustomSessionStorage.prototype = sessionStorage
. Additionally,sessionStorage
haslength
property descriptor that should be bound as well.A more general way to extend it is to provide a base class that wraps original methods and can be extended further: