const obj = {
name: 'deyang',
age: 18
}
const objProxy = new Proxy(obj, {
// 获取值时的捕获器
get(target, key) {
console.log(`监听到对象的${key}属性被访问了`, target)
return target[key]
},
// 设置值时的捕获器
set(target, key, newValue) {
console.log(`监听到对象的${key}属性被设置了`, target)
target[key] = newValue
},
// 监听 in 捕获器
has(target, key) {
console.log(`监听到对象的in操作符`, target)
return key in target
},
// 监听 delete 捕获器
deleteProperty(target, key) {
console.log(`监听到对象的delete操作符`, target)
delete target[key]
},
// 获取对象原型捕获器
getPrototypeOf(target) { },
// 设置对象原型捕获器
setPrototypeOf(target, prototype) { },
// 是否可以扩展捕获器
isExtensible() { },
// 阻止扩展捕获器
preventExtensions() { },
// 获取自己的属性描述符捕获器
getOwnPropertyDescriptor() { },
// 定义属性捕获器
defineProperty() { },
// 监听属性名和 symbol捕获器
ownKeys() { },
// 函数调用操作的捕获器,用于函数对象
apply() { },
// new 操作符捕获器,用于函数对象
construct() { }
})
// in 操作符
console.log('name' in objProxy)
// delete 操作符
delete objProxy.name
常用的四种捕获器 get、set、has、deleteProperty,以deleteProperty为例,可以监听到对象上属性的删除,这也是vue3较于vue2的一大优点
另外 apply 和 construct 捕获器是针对函数对象的操作
function foo() {
}
const fooProxy = new Proxy(foo, {
apply: function(target, thisArg, argArray) {
console.log("对foo函数进行了apply调用")
return target.apply(thisArg, argArray)
},
construct: function(target, argArray, newTarget) {
console.log("对foo函数进行了new调用")
return new target(...argArray)
}
})
fooProxy.apply({}, ["abc", "cba"])
new fooProxy("abc", "cba")
运行结果如下