ES6 - handler.construct()


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.

   class Student{
         this.firstName = firstName
         this.lastName = lastName
      get fullName(){
         return `${this.firstName} : ${this.lastName}`
   const handler = {

         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')
   const s2 = new StudentProxy('Tutorials')

The output of the above code will be as follows −

kannan : sudhakaran
Uncaught Please enter First name and Last name