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


ES6 handler.get()用法及代碼示例


下麵的例子定義了一個類Student使用構造函數和自定義 getter 方法,fullName.自定義 getter 方法通過連接firstNamelastName.該程序創建一個代理並定義一個處理程序對象,該對象在訪問屬性firstName、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

相關用法


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