ES6 - handler.get()
以下示例定义了一个类 Student,该类具有一个构造函数和一个自定义 getter 方法 fullName。自定义 getter 方法通过连接 firstName 和 lastName 返回一个新字符串。该程序创建了一个代理,并定义了一个处理程序对象,每当访问属性 firstName、lastName 和 fullName 时,该对象都会进行拦截。属性值将以大写形式返回。
<script>
class Student{
constructor(firstName,lastName){
this.firstName = firstName
this.lastName = lastName
}
get fullName(){
return `${this.firstName} : ${this.lastName}`
}
}
const handler = {
get: function(target,property){
Reflect.get(target,property).toUpperCase();
}
}
const s1 = new Student("Tutorials","Point")
const proxy = new Proxy(s1,handler)
console.log(proxy.fullName)
console.log(proxy.firstName)
console.log(proxy.lastName)
</script>
上述代码的输出将如下所示 −
TUTORIALS : POINT TUTORIALS POINT

