javascript 代理
The JavaScript Proxy API provides a wealth of "magic" within JavaScript, allowing you to use any object as sort of an alias that allows a wall of validation, formatting, and error throwing. Did you know that you could also employ the Proxy API as an abstraction to different types of storage? Whether it's sessionStorage
, localStorage
, or IndexedDB, you can use a proxy to make the API much easier to work with!
JavaScript Proxy API在JavaScript中提供了很多“魔术”,使您可以将任何对象用作别名,从而可以进行验证,格式化和错误抛出。 您是否知道还可以将Proxy API用作对不同类型的存储的抽象? 无论是sessionStorage
, localStorage
还是IndexedDB,您都可以使用代理使该API更易于使用!
A very basic usage of the Proxy API is as follows:
Proxy API的一个非常基本的用法如下:
/*
const proxy = new Proxy({}, {
get: (obj, prop) => { ... },
set: (obj, prop, value) => { ... },
// more props here
});
*/
// This basic proxy returns null instead of undefined if the
// property doesn't exist
const proxy = new Proxy({}, {
get: (obj, prop) => {
return prop in obj ? obj[prop] : null;
}
});
// proxy.whatever => null
The localStorage API is easy enough to use but employing a Proxy allows us to use the familiar object syntax and eventually even swap out the storage type without any other part of your code being effected.
localStorage API易于使用,但是使用代理可以使我们使用熟悉的对象语法,甚至可以交换存储类型,而不会影响代码的任何其他部分。
function getStorage(storage, prefix) {
return new Proxy({}, {
set: (obj, prop, value) => {
// obj[prop] = value;
storage.setItem(`${prefix}.${prop}`, value);
},
get: (obj, prop) => {
// return obj[prop];
return storage.getItem(`${prefix}.${prop}`);
},
});
}
// Create an instance of the storage proxy
const userObject = getStorage(localStorage, "user");
// Set a value in localStorage
userObject.name = "David";
// Get the value from localStorage
const { name } = userObject;
Note: The code above is a very simplistic example -- you'd also want to add methods for deleting from the object, as well as try/catch to prevent storage errors!
注意:上面的代码是一个非常简单的示例-您还希望添加用于从对象中删除的方法,以及try / catch以防止存储错误!
You could swap localStorage
for sessionStorage
and there'd be very little effect on your overall code! If you do use storage in your app, you're likely already using and abstraction, but I love the basic JavaScript object interaction pleasing.
您可以将localStorage
换成sessionStorage
,这对您的整体代码几乎没有影响! 如果您确实在应用程序中使用存储,那么您可能已经在使用和抽象了,但是我喜欢基本JavaScript对象交互。
And I'm not the only one that loves this pattern. Firefox DevTools debugger uses this pattern to abstract the IndexedDB API for storing breakpoints, tabs, and other preferences!
而且我不是唯一喜欢这种模式的人。 Firefox DevTools调试器使用此模式抽象IndexedDB API,以存储断点,选项卡和其他首选项!
javascript 代理