ES6 - handler.get()



以下示例定義了一個類 Student,包含建構函式和自定義的 getter 方法 fullName。自定義 getter 方法透過連線 firstNamelastName 返回一個新字串。該程式建立一個代理並定義一個處理物件,該物件在訪問 propertiesfirstName、lastName 和 fullName 時進行攔截。屬性值將以大寫形式返回。

<script>
   class Student{
      constructor(firstName,lastName){
         this.firstName = firstName
         this.lastName = lastName
      }
      get fullName(){
         return `${this.firstName} : ${this.lastName}`
      }
   }
   const handler = {
      get: function(target,property){
         Reflect.get(target,property).toUpperCase();
      }
   }
   const s1 = new Student("Tutorials","Point")
   const proxy = new Proxy(s1,handler)
   console.log(proxy.fullName)
   console.log(proxy.firstName)
   console.log(proxy.lastName)
</script>

以上程式碼的輸出如下 −

TUTORIALS : POINT
TUTORIALS
POINT
廣告
© . All rights reserved.