思路
- 使用
Proxy
构造函数创建代理对象,该对象用于包装目标对象。
- 在
Proxy
的 get
陷阱中,检查当前操作是否被授权进行属性读取。
- 在
Proxy
的 set
陷阱中,检查当前操作是否被授权进行属性写入。
- 在
Proxy
的 deleteProperty
陷阱中,检查当前操作是否被授权进行属性删除。
代码示例
// 目标对象
const target = {
accountBalance: 1000,
transactionHistory: []
};
// 模拟权限列表,这里假设只有 'admin' 角色有全部权限
const authorizedRoles = {
read: ['admin', 'user'],
write: ['admin'],
delete: ['admin']
};
// 当前用户角色
const currentRole = 'user';
const proxy = new Proxy(target, {
get(target, property) {
if (authorizedRoles.read.includes(currentRole)) {
return target[property];
}
throw new Error('没有读取权限');
},
set(target, property, value) {
if (authorizedRoles.write.includes(currentRole)) {
target[property] = value;
return true;
}
throw new Error('没有写入权限');
},
deleteProperty(target, property) {
if (authorizedRoles.delete.includes(currentRole)) {
delete target[property];
return true;
}
throw new Error('没有删除权限');
}
});
// 测试读取
console.log(proxy.accountBalance);
// 测试写入
try {
proxy.accountBalance = 1500;
} catch (error) {
console.error(error.message);
}
// 测试删除
try {
delete proxy.transactionHistory;
} catch (error) {
console.error(error.message);
}