ES6 - handler.has()



以下示例定義了一個類 Student,該類有一個建構函式,它將 firstNamelastName 作為引數。此程式建立一個代理,並定義一個處理程式物件。當使用 in 運算子時,就會呼叫處理程式物件的 has() 方法

<script>
   class Student{
      constructor(firstName,lastName){
         this.firstName = firstName
         this.lastName = lastName
      }
   }
   const handler = {
      has: function(target,property){
         console.log('Checking for '+property+' in the object')
         return Reflect.has(target,property)
      }
   }

   const s1 = new Student("Tutorials","Point")
   const proxy = new Proxy(s1,handler)
   console.log('firstName' in proxy)
</script>

以上程式碼的輸出如下 −

Checking for firstName in the object
true
廣告
© . All rights reserved.