Proxy and Reflection API
A proxy is a wrapper that can intercept and modify underlying JavaScript engine operations. In new languages, it exposes internal operational objects, allowing developers to create built-in objects.
| Proxy Trap | Overridden Feature | Default Feature |
|---|---|---|
| get | Read a property value | Reflect.get() |
| set | Write a property value | Reflect.set() |
| has | in operator |
Reflect.has() |
| deleteProperty | delete operator |
Reflect.deleteProperty() |
| getPropertyOf | Object.getPropertyOf() | Reflect.getPropertyOf() |
| setPropertyOf | Object.setPropertyOf() | Reflect.setPropertyOf() |
| isExtensible | Object.isExtensible() | Reflect.isExtensible() |
| preventExtensions | Object.preventExtensions() | Reflect.preventExtensions() |
| getOwnPropertyDescriptor | Object.getOwnPropertyDescriptor() | Reflect.getOwnPropertyDescriptor() |
| defineProperty | Object.defineProperty() | Reflect.defineProperty() |
| ownKeys | Object.keys() Object.getOwnPropertyNames() Object.getOwnPropertySymbols() |
Reflect.ownKeys() |
| apply | Call a function | Reflect.apply() |
| construct | Call a function with new |
Reflect.construct() |
## Creating a simple proxy
let target = {}
let proxy = new Proxy(target,{}),
proxy.name = "proxy";
console.log(proxy.name) // proxy
console.log(target.name) // proxy
target.name = "target"
console.log(proxy.name) // target
console.log(target.name) // target
Using the set trap to validate properties
Accepts 4 arguments
- trapTarget: The object that receives the property (the proxy's target)
- key: The property key to be written
- value: The value of the property being written
- receiver: The object on which the operation occurred (usually the proxy)
let target = {
name:"target"
}
let proxy = new Proxy(target,{
set(trapTarget,key,value,recevier){
// Ignore existing properties that are not intended to be affected
if(!trapTarget.hasOwnProperty(key)){
if(isNaN(value)){
throw new TypeError('Property must be a number')
}
}
// Add property
return Reflect.set(trapTarget,key,value,recevier)
}
})
proxy.count = 1;
console.log(proxy.count) // 1
console.log(target.count) // 1
// Since the target already has a name property, it can be assigned a value
proxy.name = "proxy"
console.log(proxy.name) // proxy
console.log(target.name) // proxy
// Assigning a value to a non-existent property will throw an error
proxy.otherName = "proxy"
I don't want to look at the rest... maybe later.
主题测试文章,只做测试使用。发布者:Walker,转转请注明出处:https://walker-learn.xyz/archives/4340