当前位置:网站首页>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;
}
})
边栏推荐
- More information about M91 fast hall measuring instrument
- Lake shore M91 fast hall measuring instrument
- English grammar_ Adjective / adverb Level 3 - precautions
- PostgreSQL varchar[] array type operation
- Ubuntu14 install MySQL and configure root account local and remote access
- Is PMP cancelled??
- Junit单元测试框架详解
- 物联网平台thingsboard搭建学习记录
- ECS summer money saving secret, this time @ old users come and take it away
- 使用环信提供的uni-app Demo,快速实现一对一单聊
猜你喜欢
pickle.load报错【AttributeError: Can‘t get attribute ‘Vocabulary‘ on <module ‘__main__‘】
The intelligent epidemic prevention system provides safety guarantee for the resumption of work and production at the construction site
Manufacturing SRM management system supplier all-round closed-loop management, to achieve procurement sourcing and process efficient collaboration
PMP是被取消了吗??
Superoptimag superconducting magnet system - SOM, Som2 series
寶,運維100+服務器很頭疼怎麼辦?用行雲管家!
新版国标GB28181视频平台EasyGBS如何配置WebRTC视频流格式播放?
How to solve the problem of splash screen when the main and sub code streams of easygbs are h.265?
商业智能BI开发和报表开发有什么本质区别?
Junit单元测试框架详解
随机推荐
EasyGBS主子码流都为H.265时,切换出现花屏如何解决?
uni-app微信小程序一键登录获取权限功能
Ubuntu14 install MySQL and configure root account local and remote access
PMP是被取消了吗??
研究了11种实时聊天软件,我发现都具备这些功能…
从零开始学 MySQL —数据库和数据表操作
Lake Shore M91快速霍尔测量仪
The intelligent epidemic prevention system provides safety guarantee for the resumption of work and production at the construction site
案例分享:QinQ基本组网配置
Solidity - contract structure - error - ^0.8.4 NEW
寶,運維100+服務器很頭疼怎麼辦?用行雲管家!
Write it down once Net travel management background CPU Explosion Analysis
Chinese and English instructions human soluble advanced glycation end products receptor (sRAGE) ELISA Kit
白盒加密技术浅理解
axure不显示元件库
How to solve the problem of splash screen when the main and sub code streams of easygbs are h.265?
Dlib+opencv library for fatigue detection
【森城市】GIS数据漫谈(一)
M91 fast hall measuring instrument - better measurement in a shorter time
The former 4A executives engaged in agent operation and won an IPO