當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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

相關用法


注:本文由純淨天空篩選整理自 ES6 - handler.construct()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。