Object.defineProperty
- 通常来说当x=1或者x++这种赋值操作会触发set;但是x=1这种直接赋值的方式不会触发get,而x++的方式会触发get
- get、set 无法监听属性删除
const obj = {
name: 'xjt',
age: 22
}
Object.defineProperty(obj, 'name', {
get() {
console.log('get');
return 99
},
set() {
console.log('set');
}
})
delete obj.name
console.log(obj);
//obj = {age: 22} ,name属性成功删除但get、set并未打印
Proxy
- Proxy实例 deleteProperty方法用于拦截delete操作,但如果这个方法抛出错误或者返回false,当前属性就无法被delete命令删除。
const obj = {
name: 'xjt',
age: 22
}
var proxy = new Proxy(obj, {
get(target, propKey) {
console.log('get:', propKey);
},
set() {
console.log('set');
},
deleteProperty(target, key) {
delete target[key];
console.log('delete');//delete
}
});
delete proxy.age
console.log(obj);//{name: "xjt"}