当前位置:网站首页>JS proxy
JS proxy
2022-07-01 19:48:00 【Dragon_ qing】
JS Of Proxy
Proxy
Concept
One Proxy Object wraps another object and intercepts things like reads / Write properties and other operations , You can choose to handle them yourself , Or transparently allow the object to handle them .
Proxy Used in many libraries and some browser frameworks . In this paper , We will see many practical applications .
grammar
let proxy = new Proxy(target, handler)
Parameters
target—— Is the object to be wrapped , It could be anything , Include function .handler—— Agent configuration : with “ Catcher ”(“traps”, That is, the method of intercepting operations ) The object of . such asgetThe catcher is used to readtargetProperties of ,setThe catcher is used to writetargetProperties of , wait .Yes
proxyTo operate , If inhandlerThere is a corresponding catcher in , Then it will run , also Proxy Have the opportunity to deal with it , Otherwise, it will directly affect target To deal with .
Example
let target = {
};
let proxy = new Proxy(target, {
}); // Empty handler object
proxy.test = 5; // write in proxy object (1)
alert(target.test); // 5,test The attribute appears in target in !
alert(proxy.test); // 5, We can also from proxy Object to read it (2)
for(let key in proxy) alert(key); // test, Iterations also work (3)
Because there is no catcher , All right proxy All operations are forwarded directly to target.
- Write operation
proxy.test=Will write the value totarget. - Read operation
proxy.testFromtargetReturn the corresponding value . - iteration
proxyFromtargetReturn the corresponding value .
We can see , There are no snaps ,proxy It's a target Transparent wrapper for (wrapper).

Common traps
get
To intercept read operations ,handler Should have get(target, property, receiver) Method .
Parameters
target—— It's the target , This object is passed as the first parameter tonew Proxy,property—— Target property name ,receiver—— If the target attribute is a getter Accessor properties , bereceiverThis is where the attribute is read this timethisobject . Usually , This is it.proxyObject itself ( perhaps , If we're from proxy Inherit , From this proxy Inherited objects ).
Example :
let numbers = [0, 1, 2];
numbers = new Proxy(numbers, {
get(target, prop) {
if (prop in target) {
return target[prop];
} else {
return 0; // The default value is
}
}
});
alert( numbers[1] ); // 1 Note that if numbers = [0, 2, 1] The result is 2. Because the return is target[prop]
alert( numbers[123] ); // 0( Without this array item )
Be careful
The proxy should completely replace the target object everywhere . After the target object is proxied , No one should ever reference the target object again . Otherwise, it's easy to screw up .
set
Suppose we want an array dedicated to numbers . If you add other types of values , You should throw an error .
When writing an attribute set The catcher is triggered .
set(target, property, value, receiver)
Parameters
target—— It's the target , This object is passed as the first parameter tonew Proxy,property—— Target attribute name ,value—— The value of the target property ,receiver—— AndgetThe catcher is similar to , Only with setter Accessor properties are related .
Example
let numbers = [];
numbers = new Proxy(numbers, {
// (*)
set(target, prop, val) {
// Block write attribute operations
if (typeof val == 'number') {
target[prop] = val;
return true;
} else {
return false;
}
}
});
numbers.push(1); // Add success
numbers.push(2); // Add success
alert("Length is: " + numbers.length); // 2
numbers.push("test"); // TypeError(proxy Of 'set' return false)
alert("This line is never reached (error in the line above)");
Don't forget to return true
about set operation , It must return... On successful writing true.
Other traps
| Internal methods | Handler Method | When the trigger |
|---|---|---|
[[Get]] | get | read attribute |
[[Set]] | set | Write properties |
[[HasProperty]] | has | in The operator |
[[Delete]] | deleteProperty | delete The operator |
[[Call]] | apply | Function call |
[[Construct]] | construct | new The operator |
[[GetPrototypeOf]] | getPrototypeOf | Object.getPrototypeOf |
[[SetPrototypeOf]] | setPrototypeOf | Object.setPrototypeOf |
[[IsExtensible]] | isExtensible | Object.isExtensible |
[[PreventExtensions]] | preventExtensions | Object.preventExtensions |
[[DefineOwnProperty]] | defineProperty | Object.defineProperty, Object.defineProperties |
[[GetOwnProperty]] | getOwnPropertyDescriptor | Object.getOwnPropertyDescriptor, for..in, Object.keys/values/entries |
[[OwnPropertyKeys]] | ownKeys | Object.getOwnPropertyNames, Object.getOwnPropertySymbols, for..in, Object.keys/values/entries |
边栏推荐
- 新增订单如何防止重复提交
- HLS4ML报错The board_part definition was not found for tul.com.tw:pynq-z2:part0:1.0.
- Oracle物理体系结构
- Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?
- 2022/5/23-2022/5/30
- Linux下安装Redis,并配置环境
- Procédure de mesure du capteur d'accord vibrant par le module d'acquisition d'accord vibrant
- ModSim基本使用(Modbus模拟器)
- Remove line breaks from MySQL query results
- Axure does not display catalogs
猜你喜欢

GC垃圾回收

Flutter 实战-快速实现音视频通话应用

Oracle物理体系结构

Example explanation: move graph explorer to jupyterlab

AAAI2020: Real-time Scene Text Detection with Differentiable Binarization

面试题篇一
![[research materials] iResearch tide Watching: seven major trends in the clothing industry - Download attached](/img/c8/a205ddc2835c87efa38808cf31f59e.jpg)
[research materials] iResearch tide Watching: seven major trends in the clothing industry - Download attached

科技T3国产平台!成功搭载“翼辉国产实时系统SylixOS”

MySQl的基本使用

GaussDB(for MySQL) :Partial Result Cache,通过缓存中间结果对算子进行加速
随机推荐
ffmpeg AVFrame 转 cv::Mat
GC garbage collection
torch. nn. functional. Interpolate function
H264编码profile & level控制
【let var const】
Basic knowledge of audio coding and decoding
[exercise] HashSet
mysql 报错 Can‘t create table ‘demo01.tb_Student‘ (errno: 150)*
Linux下安装Redis,并配置环境
February 15, 2022: sweeping robot. There is a floor sweeping robot in the room (represented by a grid). Each grid in the grid has two possibilities: empty and obstacles. The sweeping robot provides fo
Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?
Bind this of the current scope for callback functions in other cases such as timers and delayers
Unreal Engine packaging project
2022/6/8-2022/6/12
有意思了!数据库也搞Serverless!
解决VSCode下载慢或下载失败的问题
tensorflow报错Could not load dynamic library ‘libcudnn.so.8
采集抖音视频
118. Yanghui triangle
博途V16 获取系统时间转换成字符串