当前位置:网站首页>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);
边栏推荐
- ZFS - 01 - basic operations of creating and expanding zpool
- 信达证券是国企吗?在信达证券开户资金安全吗?
- VIM basic operation commands
- Qtimgui 编译
- pd.melt() vs reshape2::melt()
- Interpretation of "cross chain interconnection smart contract"
- R language ggplot2 visual line, custom configuration title text related content color and legend color match (match colors of groups)
- How to build an enterprise level OLAP data engine for massive data and high real-time requirements?
- What is national debt reverse repurchase? Is it safe?
- Automatic machine learning library: Tpot の learning notes
猜你喜欢

上半年出货量已超去年全年,森思泰克毫米波雷达“夺食”国际巨头

什么是hpaPaaS平台?

Save the image with gaussdb (for redis), and the recommended business can easily reduce the cost by 60%

How developers choose the right database for react native

给生活加点惊喜,做创意生活的原型设计师丨编程挑战赛 x 选手分享

Interview shock: why does TCP need three handshakes?

如何创建一个有效的帮助文档?

Trust multithread security count

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

JVM基础和问题分析入门笔记
随机推荐
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
字符串函数和内存函数(二)
R language uses GT package and gtextras package to display tabular data beautifully: GT_ bar_ Plot function and GT_ plt_ bar_ PCT function visual percentage bar graph, percentage bar graph of original
Dynamic memory management
Interview shock: why does TCP need three handshakes?
【翻译】LFX 2022年春季导师资格开放--2月13日前申请CNCF项目!
11.1-cm24 nearest common ancestor
String function and memory function (2)
关爱一线防疫工作者,浩城嘉业携手高米店街道办事处共筑公益长城
Interpretation of "cross chain interconnection smart contract"
Northeast people know sexiness best
中信证券低佣金开户免5是真的吗,安全吗
Yarn 安装与使用教程[通俗易懂]
Introduction notes of JVM foundation and problem analysis
Advanced software testing - test classification
11.2-hj86 find the maximum number of continuous bits
Yes, UDP protocol can also be used to request DNS server
文件常用操作
Circulaindicator component, which makes the indicator style more diversified
2022 robocom provincial competition solution