ES6 - Reflect.set()



這是一個將值賦予屬性的函式。它返回一個布林值,如果更新成功則為真。

語法

下面提到的語法適用於函式set(),其中,

  • target 是要設定值的屬性的名稱。

  • propertyKey 是要獲取的屬性的名稱。

  • Receiver 是如果遇到 setter,則為對 target 的呼叫提供的 this 值。這是一個可選引數。

Reflect.set(target, propertyKey, value[, receiver])

示例

以下示例使用反射建立 Student 類的例項,並使用Reflect.set()方法設定例項屬性的值。

<script>
   class Student{
      constructor(firstName,lastName){
         this.firstName = firstName
         this.lastName = lastName
      }
      get fullName(){
         return `${this.firstName} : ${this.lastName}`
      }
   }

   const args = ['Tutorials','']
   const s1 = Reflect.construct(Student,args)
   console.log('fullname is ',Reflect.get(s1,'fullName'))
   //setting value
   Reflect.set(s1,'lastName','Point')
   console.log('fullname is ',Reflect.get(s1,'fullName'))
</script>

以上程式碼的輸出將如下所示:

fullname is Tutorials :
fullname is Tutorials : Point
廣告

© . All rights reserved.