ES6 - handler.construct()



下面的例子定义了一个有构造方法和 getter 方法的类 Student。构造方法接受 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
广告