ES6 - handler.set()



以下是使用建構函式和自定義 getter 方法(fullName)定義類 Student 的示例。建構函式使用 firstName 和 lastName 作為引數。該程式建立了一個代理,並定義了一個在 firstName 和 lastName 上攔截所有 set 操作的 handler 物件。如果屬性值長度不超過 2,該 handler 物件將丟擲一個錯誤。

<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
廣告
© . All rights reserved.