ES6 - handler.set()
以下示例定义了一个 Student 类,该类具有一个构造函数和一个自定义 getter 方法 fullName。构造函数以 firstName 和 lastName 作为参数。该程序创建一个代理并定义一个处理程序对象,该对象拦截 firstName 和 lastName 上的所有设置操作。如果属性值的长度不大于 2,处理程序对象将抛出错误。
<script>
class Student{
constructor(firstName,lastName){
this.firstName = firstName
this.lastName = lastName
}
get fullName(){
return `${this.firstName} : ${this.lastName}`
}
}
const handler = {
set: function(target,property,value){
if(value.length>2){
return Reflect.set(target,property,value);
} else {
throw 'string length should be greater than 2'
}
}
}
const s1 = new Student("Tutorials","Point")
const proxy = new Proxy(s1,handler)
console.log(proxy.fullName)
proxy.firstName="Test"
console.log(proxy.fullName)
proxy.lastName="P"
</script>
上述代码的输出将如下所示 −
Tutorials : Point Test : Point Uncaught string length should be greater than 2

