ES6 - handler.construct()


Advertisements

The following example defines a class Student with a constructor and a getter method. The constructor takes firstName and lastName as parameters. The program creates a proxy and defines a handler object to intercept the constructor. The handler object verifies the number of parameters passed to the constructor. The handler object throws an error if exactly two parameters are not passed to the constructor.

<script>
   class Student{
      constructor(firstName,lastName){
         this.firstName = firstName
         this.lastName = lastName
      }
   
      get fullName(){
         return `${this.firstName} : ${this.lastName}`
      }
   }
   const handler = {
      construct:function(target,args){

         if(args.length==2) {
            return Reflect.construct(target,args);
         }
         else throw 'Please enter First name and Last name'
      }
   }
   const StudentProxy = new Proxy(Student,handler)
   const s1 = new StudentProxy('kannan','sudhakaran')
   console.log(s1.fullName)
   const s2 = new StudentProxy('Tutorials')
   console.log(s2.fullName)
</script>

The output of the above code will be as follows −

kannan : sudhakaran
Uncaught Please enter First name and Last name
Advertisements