当前位置:网站首页>Typescript object proxy use
Typescript object proxy use
2022-07-25 18:44:00 【RemoteDev】
// Empty object below {} Of get And set Property accessors to intercept
let obj=new Proxy({},{
get:function (target, p, receiver) {
console.log(` Getting object properties :${p}`);
return Reflect.get(target,p,receiver);
},
set:function (target, p, value, receiver) {
console.log(` Setting properties on object :${p}, value :${value}`);
return Reflect.set(target,p,value,receiver);
}
});
// Following pair obj The access of will enter the interception of the agent
obj.length; //get visit
obj.length=1;//set visit
let myProxy = new Proxy({},{
get:function (target,p){
return 'RemoteDev';// obtain myProxy Any object of this coder returns RemoteDev
}
});
console.log(myProxy.x);
console.log(myProxy.y);
console.log(myProxy.z);
let proxy22 = new Proxy({},{
get:(target,property)=>{
return 'hello';
}
});
console.log(proxy22.x);
let tmpObj = Object.create(proxy22);
tmpObj.p;
// Intercept at the same time get,apply,construct
let handler = {
get:function (target,p){
if(p=='prototype'){
return Object.prototype;
}
return 'Hello,Your Value:' + p;
},
apply:function (target,bind,args){
return args[0];
},
construct:function (target,args){
return {value:args[1]}
}
}
let mulProxy = new Proxy(function (x,y){return x+ y},handler);
console.log( mulProxy(1,2)) ;//apply Intercept
console.log( new mulProxy(3,4));//construct Intercept
console.log(mulProxy.prototype===Object.prototype);//get prototype Intercept
console.log(mulProxy.xxx);//get Intercept
// notes , Non writable or non configurable properties cannot be proxied
let noProxyObj=Object.defineProperties({},{
test:{
value:'test',
configurable:false,
writable:false
},
});
let xhandler = {
get:function (target,p){
return 'noProxyObj';
}
}
let tmpProxy = new Proxy(noProxyObj,xhandler);
tmpProxy.xxx;
var t = ()=>{return 'XXXX';};
let h = {
apply:function (){
return 'ZZZ';
}
};
let p = new Proxy(t,h);
p();
let p1= new Proxy(function (){
return 'hello';
},{
apply(target, thisArg, argArray) {
return ' Function proxy '
}
});
p1();
console.log('=============')
let h1 = {
has:function (t,k){
if(k[0]==='_'){
console.log(' Attributes exist _');
return false;
}
return k in t;
}
};
let t1 = {_a:'yes',b:'no'};
let r1=new Proxy(t1,h1);
console.log('_a' in r1);
let t2={a:10};
Object.preventExtensions(t2);// Forbidden object t1 Expand , Extension objects that are not configurable or prohibited cannot be proxied
let p3=new Proxy(t2,{
has:function(target, p) {
return false;
}
});
//console.log('a' in p3); // Extension objects that are not configurable or prohibited cannot be proxied ,but the proxy target is not extensible
// Be careful : for...in The loop cannot be has Intercept
let funcProxy = new Proxy(function (){console.log(' Function interception demonstration ')},{
construct(target, argArray, newTarget) {
console.log(' Function implementation interception ...');
return { value:argArray[0] *80};
}
});
console.log(new funcProxy(9).value);
let delHandler = {
deleteProperty(target, p) {
checkDel(p,'delete');
return true;
}
}
let checkDel=function(p,flag) {
if(p[0]==='_'){
throw new Error(' Successfully intercepted and deleted underlined attributes ');
};
}
let delTarget = {_a:'yes',b:'no'};
let delProxy=new Proxy(delTarget,delHandler);
//delete delProxy._a;// Delete object properties
// Add attributes to the interception object
let noAddAttr={};
let noAddHandler={
defineProperty (t,k,d) {
return false;
}
};
let noAddProxy=new Proxy(noAddAttr,noAddHandler);
noAddProxy.ok = 'ok';
let ownHandler={
getOwnPropertyDescriptor(t,k){
if(k[0]==='_'){return;}
return Object.getOwnPropertyDescriptor(t,k);
}
}
let ownTarget={_a:'yes',b:'no'};
let ownProxy= new Proxy(ownTarget,ownHandler);
let ownP = Object.getOwnPropertyDescriptor(ownProxy,'_a');//_a Attribute description is blocked
console.log(ownP);
console.log(Object.getOwnPropertyDescriptor(ownProxy,'b'));
let proto={}
let protoProxy = new Proxy({},{
getPrototypeOf(t) {
console.log('getPrototypeOf Intercept ');
return proto;
}
});
console.log(Object.getPrototypeOf(protoProxy));
let extProxy = new Proxy({},{
isExtensible(target) {
console.log('isExtensible Method blocked ');
return true;
}
});
console.log(Object.isExtensible(extProxy));
let objExt = {
x:1,y:2,z:3
};
let objExtHandler={
ownKeys(target) {
return ['y'];
}
};
let objExProxy=new Proxy(objExt,objExtHandler);
console.log( Object.keys(objExProxy));
// Enumerable attributes and Symbol The attribute of name will be filtered out by the interceptor
let myTarget= {
a:1,b:2,c:3,[Symbol.for('test')]:4
};
Object.defineProperty(myTarget,'newkey',{
value:'test',
configurable:true,
enumerable:false,
writable:true
});
let myHandler={
ownKeys(t){
return ['a','d',Symbol.for('test'),'newkey'];//d Property does not exist ,Symbol Automatic filtering , So back a attribute
}
};
let mytmpProxy = new Proxy(myTarget,myHandler);
console.log(Object.keys(mytmpProxy));
let pp= new Proxy({},{
ownKeys(t) {
return ['a','b','c'];
}
});
console.log(Object.getOwnPropertyNames(pp));
// In case of non extensibility , Cannot return properties other than objects
let obj1 = {x:1};
Object.preventExtensions(obj1);
let px = new Proxy(obj1,{
ownKeys(t) {
return ['x','y'];
}
})
//console.log(Object.getOwnPropertyNames(px));// Run time error y For attributes other than non extensible objects
let proxy1 = new Proxy({},{
preventExtensions(t) {
Object.preventExtensions(t);
return true;
}
});
console.log(Object.preventExtensions(p));
let handler1 = {
setPrototypeOf(t,p){
console.log('setPrototypeOf Intercept ');
throw new Error('setPrototypeOf Intercept ');
}
}
let proto1={};
let target1=function (){};
let proxy2=new Proxy(target1,handler1);
//Object.setPrototypeOf(proxy2,proto1);
// The agent can be cancelled
let t11={};
let h11={};
let {proxy,revoke}=Proxy.revocable(t11,h11);
console.log(proxy.x);
revoke();// Cancel object proxy
//console.log(proxy.x);// inaccessible , Agent cancelled a proxy that has been revoked
// Object proxy this Pointer problem
let thisTarget = {
m:function (){
console.log(this,proxy,this===proxy);
}
}
let thisHandler={};
let thisProxy = new Proxy(thisTarget,thisHandler);
thisTarget.m();
thisProxy.m();
let _val = new WeakMap();
class A{
constructor(v) {
_val.set(this,v);
}
get v(){
return _val.get(this);
}
}
let j=new A('j');
console.log(j.v);
let jp= new Proxy(j,{});
console.log(j.v);
// Proxy object binding
let tarDate = new Date();
let tarHandler={
// Solving the proxy object is not Date Instance problem of
get:function (t,p) {
if(p==='getDate'){
return t.getDate.bind(t);// Bound object
}
return Reflect.get(t,p);
}
};
let tarProxy=new Proxy(tarDate,tarHandler);
console.log(tarDate.getDate());
console.log(tarProxy.getDate());//tarHandler Not dealt with get Attribute , The proxy object is not Date Example
let newObject={
x:1,
y:2
}
let newObjectProxy = new Proxy(newObject,{
get(t,p){
console.log('get:',t,p);
return Reflect.get(t,p);
},
deleteProperty(t, p) {
console.log('delete:' + p.toString());
return Reflect.deleteProperty(t,p);
},
has(t, p) {
console.log('has:' + p.toString());
return Reflect.has(t,p);
}
});
console.log('x' in newObjectProxy);
delete newObjectProxy['x'];
console.log('x' in newObjectProxy);
console.log(newObjectProxy.y);
边栏推荐
- There was an error while marking a file for deletion
- With a financing of 200million yuan, the former online bookstore is now closed nationwide, with only 3 stores left in 60 stores
- Practice of RTC performance automation tool in memory optimization scenario
- PHP 中的跨站请求伪造
- Address book (I)
- 如何创建一个有效的帮助文档?
- 11.2-hj86 find the maximum number of continuous bits
- 通讯录(一)
- How high are the young people in this class for "ugly things"?
- Regex 正则表达式
猜你喜欢

《21天精通TypeScript-4》-类型推断与语义检查

3DE reply

How developers choose the right database for react native

15. Simple salary management system design

浏览器内核有几种,浏览器版本过低怎么升级

With a market value of 30billion yuan, the largest IPO in Europe in the past decade was re launched on the New York Stock Exchange

rust多线程安全计数

Add a little surprise to life and be a prototype designer of creative life -- sharing with X contestants in the programming challenge

Introduction notes of JVM foundation and problem analysis

Visual model network connection
随机推荐
Project: serial port receiving RAM storage TFT display (complete design)
软件测试——常用的测试工具
市值300亿,欧洲十年来最大IPO再冲纽交所
How developers choose the right database for react native
[QNX Hypervisor 2.2用户手册]9.5 dump
VC/PE正跑向青岛
Communication between processes (pipeline communication)
Detailed introduction and application of GaN (comprehensive and complete)
Northeast people know sexiness best
Optimistic lock resolution
What is the difference between GB and gib disk space units?
Vc/pe is running towards Qingdao
#夏日挑战赛#【FFH】这个盛夏,来一场“清凉”的代码雨!
rust多线程安全计数
Insufficient space on Disk C mklink solves vscode expansion migration to other disks
JVM基础和问题分析入门笔记
Flexible current probe selection guide
[Huawei machine test real question] string matching
文件常用操作
Practice of RTC performance automation tool in memory optimization scenario