ES6个人笔记记录——Proxy5

this问题

虽然Proxy可以代理针对目标对象的访问,但他不是目标对象的透明代理,即不做任何拦截的情况下也无法保证与目标对象的行为一致。主要原因就是在Proxy代理的情况下,目标对象内部的this关键字会指向Proxy代理

const target = {
	m : function(){
		console.log(this === proxy);
	}
};

const handler = {};

const proxy = new Proxy(target,handler);

target.m();
proxy.m();

由于this指向的变化导致Proxy无法代理目标对象

console.log('----------------------eg2------------------------');
const _name = new WeakMap();

class person{
	constructor(name){
		_name.set(this,name);
	}
	get name(){
		return _name.get(this);
	}
}

const jane = new person('jane');
console.log(jane.name);
const proxy1 = new Proxy({},jane);
console.log(proxy.name);

目标对象jane的name属性实际保存在外部Weakmap对象_name上面,通过this键区分。

由于通过proxy.name访问时,this指向proxy,导致无法取值,所以返回undefined

某些原生对象的内部属性只有通过正确this才能获取,所以Proxy也无法代理原生对象属性

Error
const target = new Date();
const handler = {};
const proxy = new Proxy(target,handler);
proxy.getDate(); 
const target2 = new Date();
const handler1 = {
	get(target,prop){
		if(prop === 'getDate'){
			return target.getDate.bind(target);
		}
		return Reflect.get(target,prop);
	}
};

const proxy2 = new Proxy(target2,handler1);
console.log(proxy2.getDate());

适合做Web服务的客户端,也可以来实现数据库的ORM层

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值