当前位置:网站首页>Analysis of proxy usage of ES6 new feature
Analysis of proxy usage of ES6 new feature
2022-07-03 04:46:00 【Aurora Borealis night.】
One . What is? Proxy:
- Proxy The object is ES6 A new feature , A proxy for creating an object , So as to achieve the interception and customization of basic operations ( Such as attribute search 、 assignment 、 enumeration 、 Function calls, etc ).
- What we need to know is , stay Vue2 Principle of bidirectional data binding in ( The data was hijacked ) use Object.defineProperty, And in the Vue3 The data hijacking principle in is Proxy agent .
Why? Proxy Will replace Object.defineProperty:
- Object.defineProperty Only the properties of the object can be hijacked , Can't listen to arrays . Not right es6 A new creation Map,Set These data structures make listening . You can't listen to add and delete operations .
- Proxy You can listen directly to the entire object instead of the attribute , You can monitor the changes of the array , Have as much as 13 Interception method in .
Use :
let p = new Proxy(target, handler);
The parameter target Target object for packaging ( It can be any kind of object , Including native arrays , function , Even another agent ).
The parameter handler For specific operation , It's actually an object , Its property is a function that defines the behavior of the agent when an operation is performed . That is to say, it writes various interception functions . Different interception methods intercept different operations .
Two . Specific interception methods :
1.get Method :
get(target, property, receiver) Method is used to block the read operation of a property , Three parameters are acceptable , They are the target objects 、 Attribute name and proxy The instance itself . See if the following example can intercept :
let obj = {
name: "jack", age: "20" };
// to obj Set up an agent
let p = new Proxy(obj, {
get(target, property) {
console.log(" I stopped " + target + " Read " + property);
console.log(" Its value is " + target[property]);
// Define the value you want to return
return target[property];
},
});
// Read obj Of age Properties , Note that after defining the proxy, you have to use the proxy to call properties or methods
console.log(p.age);
give the result as follows , It can be found that when we want to output obj.age When I was proxy The agent intercepted , And we can act as agents get Method to customize what is actually returned . That is, although you read obj.age The value of is 20, But I can intercept through proxy , You can return as many as you want , Of course, what we return above is the real value target[property] :
2. set Method :
set(target, property, value, receiver) Method is used to block the assignment of a property , The four parameters are the target object in turn 、 Property name 、 Property values and Proxy The instance itself , The last parameter is optional . Here's an example :
let obj = {
name: "jack", age: "20" };
let p = new Proxy(obj, {
set(target, property, value) {
console.log(" To set object properties ? I intercepted ~");
console.log(" It's going to change to " + value + "?");
console.log(" I won't change it for you , I changed it to 666");
target[property] = 666;
},
get(target, property) {
return target[property];
},
});
// modify obj.age The value of is 30;
p.age = 30;
// Read obj Of age Properties , Note that after defining the proxy, you have to use the proxy to call properties or methods
console.log(p.age);
You can see , I want to change obj.age by 30, But it didn't work , Because I am intercepting set In the way age Value changed to 666 了 , therefore age The value has become 666:
3.apply Method :
apply Method can intercept function calls 、call and apply operation .apply(target, thisArg, argumentsList) Three parameters , They are the target objects 、 Context object when called 、 Called parameter array . as follows :
function add(a, b) {
console.log(a + b);
}
// to add Function to set a proxy
let p = new Proxy(add, {
apply(target, thisArg, argumentsList) {
console.log(" Intercept ");
// Normally, it should be set as follows :
target.apply(this.Arg, argumentsList);
},
});
p(1, 2);
p.call(null, 13, 22);
p.apply(null, [5, 3]);
You can see , Function call ,call call ,apply call , Have implemented the agent apply Code defined in method :
4.constructor Method :
construct(target, argumentsList, newTarget) Intercept is new operation ,target Target audience ,argumentsList parameter list ,newTarget Constructor originally called . Simply put, interception new A constructor method .
function Animal(name) {
this.name = name;
}
let p = new Proxy(Animal, {
construct(target, argumentsList, newTarget) {
// I directly return an empty object
return {
};
},
});
//new One Animal example
let dog = new p("dog");
console.log(dog);
give the result as follows , Intercept successful , Modify and return :
There will be no more demonstrations , It's all the same . in general Proxy The agent can realize the interception and customization of basic operations ( Such as attribute search 、 assignment 、 enumeration 、 Function calls, etc ).
13 The two interception methods are as follows ( The following quotation is taken from Ruan Yifeng ES6 introduction ):
1、get(target, propKey, receiver):
Block the reading of object properties , such as proxy.foo and proxy[‘foo’].
2、set(target, propKey, value, receiver): Setting of intercepting object properties , such as proxy.foo =
v or proxy[‘foo’] = v, Returns a Boolean value .3、has(target, propKey):
Intercept propKey in proxy The operation of , Returns a Boolean value .
4、deleteProperty(target, propKey):
Intercept delete proxy[propKey] The operation of , Returns a Boolean value .
5、ownKeys(target):
Intercept Object.getOwnPropertyNames(proxy)、Object.getOwnPropertySymbols(proxy)、Object.keys(proxy)、for…in loop , Returns an array . This method returns the property names of all the properties of the target object , and Object.keys() The return result of contains only the traversable properties of the target object itself .
6、getOwnPropertyDescriptor(target, propKey):
Intercept Object.getOwnPropertyDescriptor(proxy, propKey), Returns the description object of the property .
7、defineProperty(target, propKey, propDesc):
Intercept Object.defineProperty(proxy, propKey,
propDesc)、Object.defineProperties(proxy, propDescs), Returns a Boolean value .8、preventExtensions(target):
Intercept Object.preventExtensions(proxy), Returns a Boolean value .
9、getPrototypeOf(target):
Intercept Object.getPrototypeOf(proxy), Return an object .
10、isExtensible(target):
Intercept Object.isExtensible(proxy), Returns a Boolean value .
11、setPrototypeOf(target, proto):
Intercept Object.setPrototypeOf(proxy,
proto), Returns a Boolean value . If the target object is a function , Then there are two additional operations to intercept .12、apply(target, object, args):
Intercept Proxy Instance as an operation of a function call , such as proxy(…args)、proxy.call(object,
…args)、proxy.apply(…).13、construct(target, args):
Intercept Proxy Operation called by instance as constructor , such as new proxy(…args).
3、 ... and . summary :
Above is proxy Some usage of . To make a long story short ,Proxy The object is ES6 A new feature , A proxy for creating an object , So as to achieve the interception and customization of basic operations ( Such as attribute search 、 assignment 、 enumeration 、 Function calls, etc ). stay Vue3 The data hijacking principle in is Proxy agent .Proxy You can listen directly to the entire object instead of the attribute , You can monitor the changes of the array , Have as much as 13 Interception method in .
See you next time ~
My Bili Bili space
Gitee Warehouse address : All special effects source code
Q Group chat ( welcome ):629596039
Other articles :
~ Follow me to see more simple creative special effects :
Text smoke effect html+css+js
Load effects around reflections html+css
Bubble floating background effect html+css
Simple clock effects html+css+js
Cyberpunk style buttons html+css
Imitating the rotation map of Netease cloud official website html+css+js
Water wave loading animation html+css
Navigation bar scrolling gradient effect html+css+js
Turn the pages of a book html+css
3D Stereo album html+css
Neon drawing board effect html+css+js
Remember some css Attribute summary ( One )
Sass Summary notes
… wait
Go to my homepage to see more ~
边栏推荐
- Games101 Lesson 9 shading 3 Notes
- 论文阅读_中文医疗模型_ eHealth
- "Niuke brush Verilog" part II Verilog advanced challenge
- stm32逆向入门
- C Primer Plus Chapter 10, question 14 3 × 5 array
- Php+mysql registration landing page development complete code
- 2022 chemical automation control instrument examination summary and chemical automation control instrument certificate examination
- Priv app permission exception
- Literature reading_ Research on the usefulness identification of tourism online comments based on semantic fusion of multimodal data (Chinese Literature)
- JVM原理简介
猜你喜欢
Leetcode simple question: check whether two string arrays are equal
Asp access teaching management system design finished product
2022 chemical automation control instrument examination summary and chemical automation control instrument certificate examination
After job hopping at the end of the year, I interviewed more than 30 companies in two weeks and finally landed
论文阅读_ICD编码_MSMN
Mobile terminal - uniapp development record (public request encapsulation)
[XSS bypass - protection strategy] understand the protection strategy and better bypass
The usage of micro service project swagger aggregation document shows all micro service addresses in the form of swagger grouping
[free completion] development of course guidance platform (source code +lunwen)
UiPath实战(08) - 选取器(Selector)
随机推荐
Preparation for school and professional cognition
普通本科大学生活避坑指南
Employee attendance management system based on SSM
Internationalization and localization, dark mode and dark mode in compose
论文阅读_中文NLP_ELECTRA
[PHP vulnerability weak type] basic knowledge, PHP weak equality, error reporting and bypassing
The reason why the entity class in the database is changed into hump naming
Market status and development prospect prediction of the global fire hose industry in 2022
雇佣收银员(差分约束)
The programmer went to bed at 12 o'clock in the middle of the night, and the leader angrily scolded: go to bed so early, you are very good at keeping fit
Career planning of counter attacking College Students
Thesis reading_ ICD code_ MSMN
[tools run SQL blind note]
2022 a special equipment related management (elevator) analysis and a special equipment related management (elevator) simulation test
When using the benchmarksql tool to preheat data for kingbasees, execute: select sys_ Prewarm ('ndx_oorder_2 ') error
2022 registration of G2 utility boiler stoker examination and G2 utility boiler stoker reexamination examination
Library management system based on SSM
Apache MPM model and ab stress test
AWS VPC
Use the benchmarksql tool to perform a data prompt on kingbases. The jdbc driver cannot be found