ES6 - Reflect.set() 函数

这是一个为属性赋值的函数。它返回一个布尔值,如果更新成功则为 true。

语法

下面提到的语法适用于函数 set(),其中,

  • target 是要获取要设置的值的属性的名称。

  • propertyKey 是要获取的属性的名称。

  • Receiver 是如果遇到 setter,则为对 target 的调用提供的值。这是一个可选参数。

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'))
   //设定值
   Reflect.set(s1,'lastName','Point')
   console.log('fullname is ',Reflect.get(s1,'fullName'))
</script>

上述代码的输出将如下所示 −

fullname is Tutorials :
fullname is Tutorials : Point