ES6 - handler.set ()
L'esempio seguente definisce una classe Student con un costruttore e un metodo getter personalizzato, fullName. Il costruttore accetta firstName e lastName come parametri. Il programma crea un proxy e definisce un oggetto gestore che intercetta tutte le operazioni di set su firstName e lastName. L'oggetto gestore genera un errore se la lunghezza del valore della proprietà non è maggiore di 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>
L'output del codice sopra sarà come mostrato di seguito -
Tutorials : Point
Test : Point
Uncaught string length should be greater than 2