当前位置:网站首页>Proxy in ES6
Proxy in ES6
2022-07-01 19:35:00 【SignalFire】
Proxy: Agent , Change the default access behavior of objects ; Add interception before the access behavior of the object , adopt Proxy The access behavior of the instance must be intercepted ; In interception, you can Set interception conditions
p() For custom functions , In the following text p() All call this function
let p = function(){
console.log(...arguments);
}
Catalog
Interceptor
| Interceptor | effect |
| get | Block the reading of object properties , Such as obj.key,obj['key'], Return property value |
| set | Setting of interception property , Returns a Boolean value |
| has | Intercept key in obj The operation of , Returns a Boolean value |
| ownKeys | Interception traversal such as : for in loop |
One 、 Array proxy
1、 Block the operation of intercepting values
2、 Intercept setting operation , When an array is assigned a value or an element is added, an event such as :arr.push(xxx),arr[0] = xxx
let arr = [1,2,3,4,5];
arr = new Proxy(arr,{
// If the element has a return value , Otherwise return to error
get(target,prop){//target Is the object of the proxy , Here is the array arr;prop Index here
return prop in target ? target[prop] : 'error';
},
// Triggered when the value is set
set(target,prop,val){
if(typeof val === 'number'){// Is a numeric type addition , Otherwise, the report will be wrong ,
target[prop] = val;// Conditions can be modified according to actual needs
return true;
}else return false;
}
})
Two 、 Object agent
1、 Whether interception exists, such as in
let age = {
min:0,
max:143
}
age = new Proxy(age,{
has(target,prop){
return prop >= target.min && prop <= target.max;
}
})
p(23 in age);
p(144 in age);
2、 Interception traversal such as :
for in loop
Object.getOwnPropertyNames(obj);
Object.getOwnPropertySymbols(obj);
Object.keys(obj);
let user = {
name:"Asia",
age:23,
_password:'666'
}
user = new Proxy(user,{
ownKeys(target){// Put all the keys of the object with '_' The first key is filtered out , Password attributes are filtered here
return Object.keys(target).filter(key => !key.startsWith('_'));// You can customize the interception conditions as needed
}
});
for(let key in user){
p(key);
}
3、 Intercept some attributes and all operations
let u = {
name:'Asia',
age:23,
_password:'666'
}
u = new Proxy(u,{
set(obj,key,val){
if(key.startsWith('_')){
throw new Error(' Do not modify the ');
}else{
obj[key] = val;
}
},
get(obj,key){
if(key.startsWith('_')){
throw new Error(' inaccessible ');
}else{
return obj[key];
}
},
deleteProperty(obj,key){
if(key.startsWith('_')){
throw new Error(' Not delete ');
}else{
delete obj[key];
return true;
}
},
ownKeys(obj,key){
return Object.keys(obj).filter(key => !key.startsWith('_'));
}
})
try{
u._password = '000';
}catch(err){
p(err.message);
};
try{
p(u._password);
}catch(err){
p(err.message);
}
try{
delete u._password;
}catch(err){
p(err.message);
}
Object.keys(u).forEach(key => p(u[key]));
3、 ... and 、 Function proxies
Change the return value of the function
let sum = (...args) => {
let sum = 0;
args.forEach(item => {
sum += item;
});
return sum;
}
sum = new Proxy(sum,{
apply(fn,ctx,args){
return fn(...args) * 10;
}
});
p(sum(1,2,3));//60
p(sum.call(null,1,2,3));//60
p(sum.apply(null,[1,2,3]));//60
Four 、class agent
Yes new To intercept
let User = class{
constructor(name){
this.name = name;
}
}
User = new Proxy(User,{
construct(cls,args,newCls){
p('construct Intercepting ');
return new cls(...args);
}
});
p(new User('Asia'));
5、 ... and 、ES5 Agent in
Object.definePrototype(obj, Property name ,callback);
let obj = {};
let _name = '';
Object.definePrototype(obj,'name',{
set(val){
_name = val;
},
get(){
return _name;
}
})
边栏推荐
- Chinese and English instructions human soluble advanced glycation end products receptor (sRAGE) ELISA Kit
- 241. Different Ways to Add Parentheses
- Ffmpeg audio related commands
- 为什么一定要从DevOps走向BizDevOps?
- 云服务器ECS夏日省钱秘籍,这次@老用户快来领走
- PostgreSQL varchar[] array type operation
- OpenCV视频质量诊断----视频遮挡诊断
- Go语言高级
- 论文阅读【Discriminative Latent Semantic Graph for Video Captioning】
- [Mori city] random talk on GIS data (I)
猜你喜欢

Task: denial of service DOS

Summary of SQL query de duplication statistics methods

Lumiprobe free radical analysis h2dcfda instructions

What must be done in graduation season before going to Shanhai

商业智能BI开发和报表开发有什么本质区别?

XML语法、约束

wireshark报文分析tcp,ftp

XML syntax, constraints

How to solve the problem of splash screen when the main and sub code streams of easygbs are h.265?

The intelligent epidemic prevention system provides safety guarantee for the resumption of work and production at the construction site
随机推荐
The intelligent epidemic prevention system provides safety guarantee for the resumption of work and production at the construction site
Task: denial of service DOS
实现一个Prometheus exporter
Contos 7 set up SFTP to create users, user groups, and delete users
宝,运维100+服务器很头疼怎么办?用行云管家!
Instagram 为何从内容共享平台变成营销工具?独立站卖家如何利用该工具?
pickle. Load error [attributeerror: can't get attribute 'volatile' on < module '\u main']
Solidity - 合约结构 - 错误(error)- ^0.8.4版本新增
Dom4j parsing XML, XPath retrieving XML
Basic knowledge of audio coding and decoding
uni-app微信小程序一键登录获取权限功能
Crunch简介、安装,使用Crunch制作密码字典
Facebook聊单,SaleSmartly有妙招!
GB28181之SIP协议
微信小程序 navigator点击后有阴影 ,去掉navigator阴影效果
brpc理解
PostgreSQL varchar[] array type operation
Introduction and installation of crunch, and making password dictionary with crunch
【org.slf4j.Logger中info()方法】
见证时代!“人玑协同 未来已来”2022弘玑生态伙伴大会开启直播预约