在处理器中只需要取消掉set和deleteProperty的功能即可
效果图:
代码示例:
//readonly相关处理器
const readonlyHandler = {
get(target,property) {
console.log('读取了'+property+"属性")
const result = Reflect.get(target, property);
return result;
},
set(target, property, value) {
console.log("只能读取,不能修改属性"+property);
},
deleteProperty(target, property) {
console.log("只能读取,不能删除属性"+property);
}
}
function shallowReadonly(target) {
if (target && typeof target === "object") {
return new Proxy(target,readonlyHandler)
}
return target;
}
const shallowRead = shallowReadonly({ a: 1, b: { c: 2 } });
// shallowRead.a++;
// delete shallowRead.a;
// shallowRead.b.c++;
function readonly(target) {
if (target && typeof target === "object") {
if (Array.isArray(target)) {
target.forEach((item, index) => { //遍历数组,当数组元素是对象情况
target[index] = readonly(item);
})
}else { //对象情况
Object.keys(target).forEach((key) => {//遍历对象,当对象属性中还有对象
target[key] = readonly(target[key]);
})
}
return new Proxy(target,readonlyHandler)
}
return target;
}
const readOnly = readonly({ a: 1, b: { c: 2 } });
// readOnly.a++;
// delete readOnly.a;
// readOnly.b.c++;
// delete readOnly.b.c;