当前位置:网站首页>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;
}
})
边栏推荐
- Learning notes [Gumbel softmax]
- ffmpeg常用命令(二)
- Go Language Advanced
- Reading the paper [learning to discretely compose reasoning module networks for video captioning]
- ES6中的代理proxy
- Ubuntu14 install MySQL and configure root account local and remote access
- Methods of finding various limits
- 【pytorch记录】自动混合精度训练 torch.cuda.amp
- DTD modeling
- Solidity - 算术运算的截断模式(unchecked)与检查模式(checked)- 0.8.0新特性
猜你喜欢
Helium transmission line of lake shore cryostat
数字化转型企业成功的关键,用数据创造价值
Enabling "new Chinese enterprises", SAP process automation landing in China
EasyGBS网络不稳定情况下重复请求视频拉流问题的优化
Reading the paper [learning to discretely compose reasoning module networks for video captioning]
混沌工程平台 ChaosBlade-Box 新版重磅发布
The intelligent epidemic prevention system provides safety guarantee for the resumption of work and production at the construction site
Dom4j parsing XML, XPath retrieving XML
为什么一定要从DevOps走向BizDevOps?
Crunch简介、安装,使用Crunch制作密码字典
随机推荐
GB28181的NAT穿透
Flutter 实战-快速实现音视频通话应用
【6.24-7.1】写作社区精彩技术博文回顾
【Go ~ 0到1 】 第五天 7月1 类型别名,自定义类型,接口,包与初始化函数
宝,运维100+服务器很头疼怎么办?用行云管家!
241. Different Ways to Add Parentheses
Crunch简介、安装,使用Crunch制作密码字典
H264 encoding profile & level control
web开发常用的开源框架的开源协议整理
物联网平台thingsboard搭建学习记录
Intensive cultivation of channels for joint development Fuxin and Weishi Jiajie held a new product training conference
[6.24-7.1] review of wonderful technical blog posts in the writing community
【英语语法】Unit1 冠词、名词、代词和数词
奔赴山海之前,毕业季一定要做的那些事情
ffmpeg 音频相关命令
Introduction to relevant processes and functions of wechat official account development
Solution and summary of Nacos startup failure
The difference between indexof and includes
下载(导出)pdf模板文件(比如:审批单),报错:Invalid nested tag *** found, expected closing tag ***
任务:拒绝服务DoS