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


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


下麵的示例定義了一個帶有構造函數和自定義 getter 方法 fullName 的 Student 類。構造函數將 firstName 和 lastName 作為參數。該程序創建一個代理並定義一個處理程序對象,該對象攔截所有對 firstName 和 lastName 的設置操作。如果屬性值的長度不大於 2,處理程序對象會拋出錯誤。

<script>
   class Student{
      constructor(firstName,lastName){
         this.firstName = firstName
         this.lastName = lastName
      }
      get fullName(){
         return `${this.firstName}:${this.lastName}`
      }
   }
   const handler = {
      set:function(target,property,value){
         if(value.length>2){
            return Reflect.set(target,property,value);
         } else { 
	        throw 'string length should be greater than 2'
         }
      }
   }
   
   const s1 = new Student("Tutorials","Point")
   const proxy = new Proxy(s1,handler)
   console.log(proxy.fullName)
   proxy.firstName="Test"
   console.log(proxy.fullName)
   proxy.lastName="P"
</script>

上麵代碼的輸出將如下所示——

Tutorials:Point
Test:Point
Uncaught string length should be greater than 2

相關用法


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