proxy 代理
2022-07-03 本文已影响0人
无花无酒_3cd3
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="box">
</div>
<script>
var person = {
name: "张三",
sex:"男"
};
//目标对象
//处理程序对象,是来处理数据的
var proxy = new Proxy(person, {
get: function(target, propKey) {
console.log(target,propKey)
console.log(Reflect.get(target,propKey))
if (propKey in target) {
return Reflect.get(target,propKey);
} else {
throw new ReferenceError("Prop name \"" + propKey + "\" does not exist.");
}
},
set(target,propKey,value){
console.log(value,"设置")
let ref=Reflect.set(target, propKey,value)
box.innerHTML= proxy.name + person.age
return ref
}
});
//通过代理对象,查询和设置目标对象的某个属性。
console.log(proxy.name ) // "张三"
proxy.name="王五"
proxy.age=20
console.log(proxy)
console.log(person)
// proxy.baba // 抛出一个错误
// Reflect.get(target,propKey)=target[propKey]
// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect/get
</script>
</body>
</html>