当前位置:网站首页>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 |
边栏推荐
- [SQL optimization] the difference between with as and temporary tables
- 实例讲解将Graph Explorer搬上JupyterLab
- 通过js实现金字塔(星号金字塔,回文对称数字金字塔)
- How to correctly use vertx to operate redis (3.9.4 with source code analysis)
- Remove line breaks from MySQL query results
- servlet知识点
- Brpc understanding
- 一个悄然崛起的国产软件,低调又强大!
- Optimization of video streaming with repeated requests in the case of unstable easygbs network
- Is Dao safe? Build finance encountered a malicious governance takeover and was looted!
猜你喜欢
随机推荐
GB28181之SIP协议
Interview questions for audio and video positions in Dachang -- today's headline
How to configure webrtc video streaming format for easygbs, a new version of national standard gb28181 video platform?
Class loading mechanism
产品模块化设计的前世今生
Bind this of the current scope for callback functions in other cases such as timers and delayers
振弦采集模块测量振弦传感器的流程步骤
博途V16 获取系统时间转换成字符串
Bao, what if the O & M 100+ server is a headache? Use Xingyun housekeeper!
Using win7 vulnerability to crack the system login password
振弦采集模塊測量振弦傳感器的流程步驟
Procédure de mesure du capteur d'accord vibrant par le module d'acquisition d'accord vibrant
New window open page -window open
Is Dao safe? Build finance encountered a malicious governance takeover and was looted!
703. 数据流中的第 K 大元素
JDBC中如何添加事务
Time series analysis using kibana timelion
Ffmpeg common commands (2)
mysql 报错 Can‘t create table ‘demo01.tb_Student‘ (errno: 150)*
Uni app product classification









