ES6个人笔记记录——Proxy3

1.apply()

apply方法拦截函数的调用、call和apply方法

三个参数,目标对象,目标对象的上下文对象,目标对象的参数数组

let handler = {
	apply(target,ctx,args){
		return Reflect.apply(...arguments);
	}
};
// eg1
let target1 = function(){
	return 'I am a target';
}

let handler1 = {
	apply : function(){
		return 'I am the proxy';
	}
};

let p1 = new Proxy(target1,handler1);

console.log(p1());

console.log('----------------eg2---------------');
// eg2
let twice = {
	apply(target,ctx,args){
		return Reflect.apply(...arguments) * 2;
	}
};

function sum(left,right){
	return left + right;
}

let proxy1 = new Proxy(sum,twice);
console.log(proxy1(1,2),proxy1.call(null,5,6),proxy1.apply(null,[7,8]));
console.log(Reflect.apply(proxy1,null,[9,8]));

2.has

拦截HasProperty操作

即判断对象是否具有某个属性时,这个方法会生效

典型操作符是in操作符

// eg3
console.log("----------------------eg3------------------------");
let handler2 = {
	has(target,key){
		if(key[0] === '_'){
			return false;
		}
		return key in target;
	}
};

let target2 = { _prop : 'foo',prop : 'foo'};
let proxy2 = (target2,handler2);
console.log('_prop' in proxy2);

如果原对象不可配置或者禁止扩展,那么这时has拦截会报错

Object.preventExtensions(obj)

has只对in循环有效,对for…in循环不生效

// eg4
console.log('------------eg4-------------');
let stu1 = { name : 'wjy', score : '99'};
let stu2 = { name : 'ty' , score : '59'};

let handler3 = {
	has(target,prop){
		if(prop === 'score' && target[prop] < 60){
			console.log("不及格");
			return false;
		}
		return prop in target;
	}
}

let oproxy1 = new Proxy(stu1,handler3);
let oproxy2 = new Proxy(stu2,handler3);
console.log('score' in oproxy1,'score' in oproxy2);

for(let i in oproxy1){
	console.log(oproxy1[i]);
}
for(let i in oproxy2){
	console.log(oproxy2[i]);
}

你可能感兴趣的:(javascript,前端学习)