Es6-handler-construct

提供:Dev Guides
移動先:案内検索

ES6-handler.construct()

次の例では、コンストラクターとゲッターメソッドを使用してクラス Student を定義しています。 コンストラクターはパラメーターとしてfirstNameおよびlastNameを取ります。 プログラムはプロキシを作成し、コンストラクターをインターセプトするハンドラーオブジェクトを定義します。 ハンドラーオブジェクトは、コンストラクターに渡されたパラメーターの数を確認します。 ちょうど2つのパラメーターがコンストラクターに渡されない場合、ハンドラーオブジェクトはエラーをスローします。

<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