90% of people ignore one point when encapsulating Storage! Do you know what the meaning of encapsulation is?
Secondary encapsulation of Storage?
Regarding the encapsulation of Storage, it is actually a commonplace talk. Many people will encapsulate Storage twice in the project, in order to make it more convenient for developers to use localStore and sessionStorage. For example, the following is probably a case that many people have encapsulated, which encapsulates simple reading and writing, or deletion and clearing:
Why do we encapsulate?
How about we go back and think about it, why do we need to encapsulate? In fact, encapsulation serves two purposes:
- Better unified maintenance
- Makes it more convenient and mindless for users to use
But I think that in a large project and in urgent development progress, the first purpose of encapsulation is to make it more convenient and mindless for users to use. So think about the encapsulation of LocalStorage just now, it can really make it more convenient for users. , use it more brainlessly?
Let me give you an example. I want to save an object. Can I save it like this?
Obviously this is not possible, the object stored will be converted into a string [object Object]:
So I have to store and retrieve values like this, using JSON.parse and JSON.stringify to transfer:
Only by doing this can I achieve my goal:
But doesn’t this seem troublesome? The first purpose of encapsulation is to make it more convenient and mindless for users. Obviously, this will only cause more trouble for users! ! !
Some people have said that JSON.parse and JSON.stringify can be written in useLocalStorage, but this solution is only for Object, but there are actually many data types: number, string, object, set, map, date, etc. , it is unreasonable for you to write it directly in it, you have to take into account all data types! !
Type guessing logic
So, if you want to make it more convenient and brainless for users, we can encapsulate a set of type guessing logic.
First we must prepare a function, which is used to determine the data type:
But just determining the type is not enough. We must also prepare a read and save strategy for each type:
Finally just need:
- Judgment type
- Get the access policy corresponding to the type
- Execute corresponding policies when accessing
We can now try to see if we can achieve our goal:
Obviously we have achieved the effect we want:
summary
Of course, Storage encapsulation is not just a function of type guessing! And in fact, there are many hidden things about encapsulation that I have not written here. This article just wants everyone to know that when encapsulating Storage, type guessing is the most basic function. With this function, users can use it more conveniently and brainlessly. .