let origin={
x:1,
y:2
}
let proxy=new Proxy(origin,{
has:(target, key)=>{
if(key==='x')return false
return true
}
})
console.log('x' in proxy) // false
console.log('y' in proxy) // true
ownKeys:获取自身属性值
语法:
ownKeys(target)
target: 代理对象
栗子:
let origin={
x:1,
y:2
}
let proxy=new Proxy(origin,{
ownKeys:(target)=>{
return ['y']
}
})
console.log(Object.getOwnPropertyNames(proxy)) // ['y']
getPrototypeOf:获取prototype
语法:
getPrototypeOf(target)
target: 代理对象
栗子
let origin={
x:1,
y:2
}
let proxy=new Proxy(origin,{
getPrototypeOf:(target)=>{
return null
}
})
console.log(Object.getPrototypeOf(p)) // null
setPrototypeOf:设置prototype
语法:
setPrototypeOf(target, prototype)
target: 代理对象
prototype: 要设置的prototype
栗子
let origin={
x:1,
y:2
}
let proxy=new Proxy(origin,{
setPrototypeOf:(target, prototype)=>{
throw 'no'
}
})
Object.setPrototypeOf(proxy, {}) // Uncaught no
defineProperty :设置属性描述
语法:
defineProperty(target, prop, descriptor)
target: 代理对象
prop: 要设置描述的属性
descriptor: 描述
栗子
let origin={}
let proxy=new Proxy(origin,{
defineProperty:(target, prop, descriptor)=>{
throw 'no'
}
})
Object.defineProperty(proxy, 'x', {configurable: true}) // Uncaught no
getOwnPropertyDescriptor :获取自身属性描述
语法:
getOwnPropertyDescriptor(target, prop)
target: 代理对象
prop: 获取描述的属性
栗子
let origin={}
let proxy=new Proxy(origin,{
getOwnPropertyDescriptor:(target, prop)=>{
throw 'no'
}
})
Object.getOwnPropertyDescriptor(proxy, 'x') // Uncaught no
isExtensible:判断是否可扩展
语法:
isExtensible(target)
target: 代理对象
栗子
let origin={}
let proxy=new Proxy(origin,{
isExtensible:(target)=>{
return false
}
})
console.log(Object.isExtensible(proxy)); // false
preventExtensions :阻止扩展
语法:
preventExtensions(target)
target: 代理对象
栗子:
let origin={}
let proxy=new Proxy(origin,{
preventExtensions:(target)=>{
return false;
}
})
console.log(Object.preventExtensions(proxy)); // Uncaught TypeError: 'preventExtensions' on proxy: trap returned falsish
construct:构造
语法:
construct(target, argumentsList, newTarget)
target: 代理对象
argumentsList: 参数列表
newTarget: 新对象
栗子:
let Origin=function(){}
let OriginProxy=new Proxy(Origin,{
construct: function(target, argumentsList, newTarget) {
throw 'error'
}
})
new OriginProxy() // Uncaught error
apply:调用
语法:
apply(target, thisArg, argumentsList)
target: 代理对象
thisArg: 上下文
argumentsList: 参数列表
栗子:
let origin=function(){}
let proxy=new Proxy(origin,{
apply: function(target, thisArg, argumentsList) {
throw 'error'
}
})
origin() // Uncaught error