当前位置:网站首页>ES6中的代理proxy
ES6中的代理proxy
2022-07-01 18:45:00 【SignalFire】
Proxy:代理器,改变对象的默认访问行为;在对象的访问行为之前增设拦截,通过Proxy实例进行的访问行为都必须经过设置的拦截;在拦截中可以根据需要 设置拦截条件
p()为自定义函数,后文中的p()都是调用这个函数
let p = function(){
console.log(...arguments);
}
目录
拦截器
拦截器 | 作用 |
get | 拦截对象属性的读取,如obj.key,obj['key'],返回属性值 |
set | 拦截属性的设置,返回布尔值 |
has | 拦截key in obj的操作,返回布尔值 |
ownKeys | 拦截遍历如: for in 循环 |
一、数组代理
1、拦截获取值的操作
2、拦截设置操作,给数组赋值或者添加元素时触发如:arr.push(xxx),arr[0] = xxx
let arr = [1,2,3,4,5];
arr = new Proxy(arr,{
//如果元素存在返回值,否则返回error
get(target,prop){//target为代理的对象,此处为数组arr;prop此处为索引
return prop in target ? target[prop] : 'error';
},
//设置值时触发
set(target,prop,val){
if(typeof val === 'number'){//是数值类型添加,否则报错,
target[prop] = val;//可根据实际需要修改条件
return true;
}else return false;
}
})
二、对象代理
1、拦截是否存在如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、拦截遍历如:
for in 循环
Object.getOwnPropertyNames(obj);
Object.getOwnPropertySymbols(obj);
Object.keys(obj);
let user = {
name:"Asia",
age:23,
_password:'666'
}
user = new Proxy(user,{
ownKeys(target){//将对象的所有键中以'_'开头的键过滤掉,此处过滤了密码属性
return Object.keys(target).filter(key => !key.startsWith('_'));//可根据需要自定义拦截条件
}
});
for(let key in user){
p(key);
}
3、拦截某些属性一切操作
let u = {
name:'Asia',
age:23,
_password:'666'
}
u = new Proxy(u,{
set(obj,key,val){
if(key.startsWith('_')){
throw new Error('不可修改');
}else{
obj[key] = val;
}
},
get(obj,key){
if(key.startsWith('_')){
throw new Error('不可访问');
}else{
return obj[key];
}
},
deleteProperty(obj,key){
if(key.startsWith('_')){
throw new Error('不可删除');
}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]));
三、函数代理
改变函数返回值
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
四、class代理
对new进行拦截
let User = class{
constructor(name){
this.name = name;
}
}
User = new Proxy(User,{
construct(cls,args,newCls){
p('construct 正在拦截');
return new cls(...args);
}
});
p(new User('Asia'));
五、ES5中的代理
Object.definePrototype(obj,属性名,callback);
let obj = {};
let _name = '';
Object.definePrototype(obj,'name',{
set(val){
_name = val;
},
get(){
return _name;
}
})
边栏推荐
- What must be done in graduation season before going to Shanhai
- 记一次 .NET 差旅管理后台 CPU 爆高分析
- 【org.slf4j.Logger中info()方法】
- PostgreSQL varchar[] 数组类型操作
- Solidity - contract structure - error - ^0.8.4 NEW
- Introduction to relevant processes and functions of wechat official account development
- 精耕渠道共謀發展 福昕攜手偉仕佳傑開展新產品培訓大會
- Lake Shore - crx-em-hf low temperature probe station
- English语法_形容词/副词3级 -注意事项
- Intensive cultivation of channels for joint development Fuxin and Weishi Jiajie held a new product training conference
猜你喜欢
Love business in Little Red Book
新版国标GB28181视频平台EasyGBS如何配置WebRTC视频流格式播放?
从零开始学 MySQL —数据库和数据表操作
机械设备行业数字化供应链集采平台解决方案:优化资源配置,实现降本增效
nacos启动失败问题解决与总结
Lake shore M91 fast hall measuring instrument
数商云:从规划到落地,五矿集团如何快速构建数字化发展新格局?
如何正确使用Vertx操作Redis(3.9.4带源码分析)
SuperOptiMag 超导磁体系统 — SOM、SOM2 系列
The intelligent epidemic prevention system provides safety guarantee for the resumption of work and production at the construction site
随机推荐
机械设备行业数字化供应链集采平台解决方案:优化资源配置,实现降本增效
Native JS creates a calendar - supports mouse wheel scrolling to select months - and can be ported to any framework
nacos配置文件发布失败,请检查参数是否正确的解决方案
PostgreSQL varchar[] array type operation
Intensive cultivation of channels for joint development Fuxin and Weishi Jiajie held a new product training conference
Solidity - truncated and checked modes of arithmetic operations - new features of 0.8.0
案例分享:QinQ基本组网配置
Lake Shore M91快速霍尔测量仪
Bao, que se passe - t - il si le serveur 100 + O & M a mal à la tête? Utilisez le majordome xingyun!
【英语语法】Unit1 冠词、名词、代词和数词
uni-app商品分类
transform + asm资料
What must be done in graduation season before going to Shanhai
ECS summer money saving secret, this time @ old users come and take it away
Lake Shore - crx-em-hf low temperature probe station
ddr4测试-2
测试自学人必看:软件测试如何找测试项目?
赋能「新型中国企业」,SAP Process Automation 落地中国
Implement a Prometheus exporter
云服务器ECS夏日省钱秘籍,这次@老用户快来领走