ES6 - handler.set()



The following example defines a class Student with a constructor and a custom getter method, fullName. The constructor takes firstName and lastName as parameters. The program creates a proxy and defines a handler object which intercepts all set operations on firstName and lastName. The handler object throws an error if the length of the property value is not greater than 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>

The output of the above code will be as shown below −

Tutorials : Point
Test : Point
Uncaught string length should be greater than 2
Advertisements