概述
proxy 意為代理府适,在目標(biāo)對(duì)象之前設(shè)置一層攔截。當(dāng)直接訪問(wèn)
proxy
的對(duì)象拓瞪,沒(méi)有啥問(wèn)題官份。當(dāng)訪問(wèn)被代理的對(duì)象只厘,其實(shí)是從proxy
那里拿答案
基礎(chǔ)使用
var person = {
name: 'yf'
}
var proxy = new Proxy(person,{
get: function (target,property) {
if (property in target) {
return target[property];
}else {
throw new ReferenceError("Property \" "+property + "\" does not exist.");
}
}
});
proxy.name // yf
proxy.age // 報(bào)錯(cuò)
注意點(diǎn)
- 當(dāng)
Proxy
的第二個(gè)參數(shù)為{}
,那么proxy
對(duì)象直達(dá)代理對(duì)象 - 當(dāng)屬性不可讀和不可配置時(shí)舅巷,使用
proxy
代理報(bào)錯(cuò)
可代理方法
下面時(shí)可以代理的方法羔味,但是參數(shù)各有不同。同時(shí)可能涉及到
Reflect
get(target,propKey,receiver)
set(target,propKey,value,receiver)
has(target,propKey)
deleteProperty(target,propkey)
ownKeys(target)
getOwnPropertyDescriptor(target,propKey)
defineProperty(target, propKey, propDesc)
preventExtensions(target)
getPrototypeOf(target)
isExtensible(target)
setPrototypeOf(target, proto)
apply(target, object, args)
construct(target, args)
this
在Proxy代理的情況下钠右,目標(biāo)對(duì)象內(nèi)部的this指向proxy代理
const target = {
m: function () {
console.log(this === proxy);
}
};
const handler = {};
const proxy = new Proxy(target,handler);
target.m() // false
prox.m() // true