当前位置:网站首页>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;
}
})
边栏推荐
- EasyGBS主子码流都为H.265时,切换出现花屏如何解决?
- Dom4J解析XML、Xpath检索XML
- 记一次 .NET 差旅管理后台 CPU 爆高分析
- uni-app商品分类
- Lumiprobe cell imaging study PKH26 cell membrane labeling kit
- [pytorch record] automatic hybrid accuracy training torch cuda. amp
- axure不显示元件库
- 狼人杀攻略:你当我好骗吗,我们相信谁!
- English grammar_ Adjective / adverb Level 3 - precautions
- GB28181的NAT穿透
猜你喜欢
Chaos engineering platform chaosblade box new heavy release
Introduction and installation of crunch, and making password dictionary with crunch
【To .NET】C#集合类源码解析
【pytorch记录】自动混合精度训练 torch.cuda.amp
pickle.load报错【AttributeError: Can‘t get attribute ‘Vocabulary‘ on <module ‘__main__‘】
Enabling "new Chinese enterprises", SAP process automation landing in China
Solidity - 算术运算的截断模式(unchecked)与检查模式(checked)- 0.8.0新特性
求各种极限的方法
XML语法、约束
[pytorch record] automatic hybrid accuracy training torch cuda. amp
随机推荐
【To .NET】C#集合类源码解析
Boost the development of digital economy and consolidate the base of digital talents - the digital talent competition was successfully held in Kunming
Opencv video quality detection -- sharpness detection
Witness the times! "The future of Renji collaboration has come" 2022 Hongji ecological partnership conference opens live broadcast reservation
Go Language Advanced
Interview questions for audio and video positions in Dachang -- today's headline
brpc理解
Lumiprobe free radical analysis h2dcfda instructions
Ffmpeg common commands (2)
sql查询去重统计的方法总结
uni-app商品分类
Chaos engineering platform chaosblade box new heavy release
What must be done in graduation season before going to Shanhai
Junit单元测试框架详解
音频编解码基础知识
Write it down once Net travel management background CPU Explosion Analysis
智慧防疫系统为建筑工地复工复产提供安全保障
uni-app微信小程序一键登录获取权限功能
Task: denial of service DOS
Lumiprobe phosphide hexaethylene phosphide specification