ES6 - handler.construct()

以下示例定义了一个类 Student,该类具有一个构造函数和一个 getter 方法。构造函数以 firstName 和 lastName 作为参数。该程序创建一个代理并定义一个处理程序对象来拦截构造函数。处理程序对象验证传递给构造函数的参数数量。如果没有恰好两个参数传递给构造函数,处理程序对象将抛出错误。

<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>

上述代码的输出将如下所示 −

kannan : sudhakaran
Uncaught Please enter First name and Last name