ES6 - handler.set ()
El siguiente ejemplo define una clase Student con un constructor y un método getter personalizado, fullName. El constructor toma firstName y lastName como parámetros. El programa crea un proxy y define un objeto manejador que intercepta todas las operaciones de conjunto en firstName y lastName. El objeto controlador arroja un error si la longitud del valor de la propiedad no es mayor que 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>
La salida del código anterior será como se muestra a continuación:
Tutorials : Point
Test : Point
Uncaught string length should be greater than 2