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


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


這是一個為屬性賦值的函數。如果更新成功,它返回一個布爾值為真。

用法

下麵提到的語法是針對函數的set(),其中,

  • target是要獲取要設置的值的屬性的名稱。

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

  • Receiver如果遇到 setter,則為對目標的調用提供此值。這是一個可選參數。

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

相關用法


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