var user = {
id : 1,
name : 'Tom',
age : 10,
school : 'primary school',
sister:{
name:'Alice',
age:12
}
}
var handler = {
get(target,prop){
if(prop == 'id'){
return undefined;
}
//return target[prop];
return Reflect.get(target,prop);
},
set(target,prop,value){
if(prop == 'id' || prop == 'name' ){
console.log(`Property ${prop} modification is not allowed.`)
}else{
//target[prop] = value;
return Reflect.set(target,prop,value);
}
},
deleteProperty(target,prop){
console.log('deleteProperty is called');
return Reflect.deleteProperty(target,prop);
}
};
var proxyUser = new Proxy(user,handler);
// console.log(proxyUser)
// console.log(proxyUser.id); //undefined
// console.log(proxyUser.name); // Tom
// console.log(proxyUser.age); //10
// console.log(proxyUser.school); //primary school
// console.log(proxyUser.sister.age); //12
// 改变属性值
// proxyUser.id = 2; //Property id modification is not allowed.
// proxyUser.name = 'Jack'; //Property name modification is not allowed.
// proxyUser.age = 9;
// proxyUser.sister.age = 13;
// console.log(user);// 改变proxyUser,user里面的值也变了
// 新增属性
// proxyUser.gender = 'boy';
// console.log(user);
// delete proxyUser.age;
// console.log(user);
proxyUser.sister.age=14;//内层对象属性值更改ok
console.log(user.sister.age);
标签:4.4,console,log,proxyUser,age,prop,proxy,target,属性
From: https://www.cnblogs.com/pansidong/p/17285445.html