当前位置:网站首页>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 asget
The catcher is used to readtarget
Properties of ,set
The catcher is used to writetarget
Properties of , wait .Yes
proxy
To operate , If inhandler
There 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.test
Fromtarget
Return the corresponding value . - iteration
proxy
Fromtarget
Return 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 , bereceiver
This is where the attribute is read this timethis
object . Usually , This is it.proxy
Object 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
—— Andget
The 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 |
边栏推荐
- 利用win7漏洞进行系统登录密码破解
- 大厂音视频职位面试题目--今日头条
- 为定时器和延时器等其它情况的回调函数绑定当前作用域的this
- Technology T3 domestic platform! Successfully equipped with "Yihui domestic real-time system sylixos"
- AAAI2020: Real-time Scene Text Detection with Differentiable Binarization
- Wireshark packet analysis TCP, FTP
- Difference between redo and undo
- Remove line breaks from MySQL query results
- Optaplanner learning notes (I) case cloud balance
- 一文读懂C语言中的结构体
猜你喜欢
[research materials] Huawei Technology ICT 2021: at the beginning of the "Yuan" year, the industry is "new" -- download attached
ModSim基本使用(Modbus模拟器)
Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?
Flutter 实战-快速实现音视频通话应用
Interview questions shared in today's group
Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
windows环境 redis安装和启动(后台启动)
Procédure de mesure du capteur d'accord vibrant par le module d'acquisition d'accord vibrant
通过js实现金字塔(星号金字塔,回文对称数字金字塔)
JS 之 常用内置类的使用
随机推荐
703. The k-th element in the data flow
Regular expression =regex=regular expression
Wechat applet navigator has a shadow after clicking. Remove the shadow effect of navigator
Analysis of GetMessage underlying mechanism
GetMessage底层机制分析
Proxy in ES6
How to use console Log print text?
音频编解码基础知识
DDR4 test-2
Oracle物理体系结构
Audio and video, encoding and decoding related e-books, gadgets, packaged for free!
GB28181之SIP协议
qobject_cast用法
brpc理解
DS transunet: Dual Swing transformer u-net for medical image segmentation
Remove line breaks from MySQL query results
Optaplanner learning notes (I) case cloud balance
Example explanation: move graph explorer to jupyterlab
Mo Tianlun salon | Tsinghua qiaojialin: Apache iotdb, originated from Tsinghua, builds an open source ecological road
MySQL signale une erreur can 't create table' demo01. TB Étudiant '(errno: 150)