核心提示:1.新建proxy对象p,进行获取和赋值操作use stric;var obj = {a: 1};var p = new Proxy(obj,{ get: function(target,key){ ...
1.新建proxy对象p,进行获取和赋值操作
'use stric'; var obj = {a: 1}; var p = new Proxy(obj,{ get: function(target,key){ return 100; }, set:function(target,key,value){ console.log('触发set'); } }); console.log(p.a);//100 console.log(p.b);//100 p.a = 2;//触发set console.log(p.a);//100
取值操作:只是触发get()函数,得到该函数的返回值
赋值操作:只是触发set()函数,因为set()函数没有进行相关的赋值操作,尽管p.a=2,其作用只是触发set()函数,console.log(p.a);只能由get()函数的返回值决定。
'use stric'; var obj = {a: 1}; var p = new Proxy(obj,{ get: function(target,key){ return 100; }, set:function(target,key,value){ Reflect.set(target,key,value); } }); console.log(p.a);//100 console.log(p.b);//100 p.a = 2; console.log(p.a);//100 console.log(obj.a);//2
删除操作:执行delete使,触发deleteProperty()函数
'use stric'; var obj = {a: 1,b: 2}; var p = new Proxy(obj,{ deleteProperty:function(target,key){ if(key !== 'a'){ Reflect.deleteProperty(target,key) } } }); delete p.a; console.log(obj.a);//1 delete p.b; console.log(obj.b);//undefined
in操作:触发has()函数:
'use stric'; var obj = {a: 1, _a: 2}; var p = new Proxy(obj,{ has:function(target,key){ if(key[0]==='_'){ return false; }else{ return key in target } } }); var bool = 'a' in p; var bool2 = '_a' in p; console.log(bool);//true console.log(bool2);//fasle
apply():拦截函数
'use stric'; var target = function () { console.log('I am the target'); }; var p = new Proxy(target, { apply: function (target, ctx, args) { console.log('I am the proxy'); return Reflect.apply(target, ctx, args); } }); p();//I am the proxy //I am the target
construct():拦截new命令。construct方法返回的必须是一个对象,否则会报错。
'use stric'; function User() { console.log('thsi is class'); }; var ClassProxy = new Proxy(User, { construct: function (target, args) { console.log('thsi is ClassProxy'); return Reflect.construct(target, args); } }); new ClassProxy();//thsi is ClassProxy //thsi is class
setPrototypeOf():拦截Object.setPrototypeOf方法。
首先了解Object.setPrototypeOf(),就是给实例对象设置原型
class People{ constructor(){ } } var proto = { sayName(){} } var people = new People(); Object.setPrototypeOf(people,proto);//等价people.__proto__ = proto; console.log(people.sayName)//[Function: sayName]
Object.setPrototypeOf(proxy,proto);
class People{ constructor(){ } } var proto = { sayName(){} } var people = new People(); var proxy = new Proxy(people,{ setPrototypeOf(target, proto){ console.log('Changing the prototype of people'); return true; } }); Object.setPrototypeOf(proxy,proto);//Changing the prototype of people
getPrototypeOf():拦截获取对象原型
class People{ constructor(){ } } var proto = {} var people = new People(); var proxy = new Proxy(people,{ getPrototypeOf(target){ console.log('Get the prototype of people'); return proto; } }); console.log(Object.getPrototypeOf(proxy)===proto);//Get the prototype of people //true