Proxy 是ES6中提供的一个非常强大的功能,可以用来代理另一个对象,从而拦截、监视并修改这个对象的各种操作
首先是Proxy()的参数:
handler处理函数一都有:
propKey in proxy
操作,返回一个布尔值下面对get函数进行简单的演示:
let arr = [123,"ac","你好"]
arrPro = new Proxy(arr,{
get(target,prop){
// target 代表被代理的数组,也就是 [123,"ac","你好"]
console.log(target)
// prop 表示要访问的属性,也就是 0
console.log(prop)
return prop in target ? target[prop] : 'error'
}
})
console.log(arrPro[0])
下面对set函数进行简单的演示:
let arr = []
let arrPro = new Proxy(arr,{
set(target,prop,val){
if(typeof val === "number"){
target[prop] = val
return true
}else{
return false
}
}
})
arrPro.push(5)
console.log(arr) //[5]
下面对has函数进行简单的演示:
let range = {
start:1,
end:5
}
range = new Proxy(range,{
has(target,prop){
return prop >= target.start && prop <= target.end
}
})
console.log(2 in range) // true
console.log(6 in range) // false
get、set、deleteProperty小集合:
let user = {
name: 'ac',
age: 12,
_password: 'xxx'
}
user = new Proxy(user, {
get(target, prop) {
if (prop.startsWith('_')) {
throw new Error('不可访问')
} else {
return target[prop]
}
},
set(target, prop, val) {
if (prop.startsWith('_')) {
throw new Error('不可设置')
} else {
target[prop] = val
return true
}
},
deleteProperty(target, prop) {
if (prop.startsWith('_')) {
throw new Error('不可删除')
} else {
delete target[prop]
return true
}
}
})
console.log(user.age) //12
console.log(user._password) //Error:不可访问
user.age = 22
console.log(user.age) //22
delete user.age
console.log(user.age) //undefined
下面对apply函数进行简单的演示:
let sum = (...args) =>{
let num = 0
args.forEach(item =>{
num += item
})
return num
}
sum = new Proxy(sum,{
apply(target,ctx,args){
return target(...args) * 2
}
})
console.log(sum(2,5)) //14
console.log(sum.call(null,2,5)) //14
console.log(sum.apply(null,[2,5])) //14
下面对construct函数进行简单的演示:
let User = class {
constructor(name){
this.name = name
}
}
User = new Proxy(User,{
construct(target,args,newTarget){
console.log("代理拦截") //代理拦截
return new target(...args) //User {name: 'ac'}
}
})
console.log(new User('ac'))